From 363542a3f0ddb9c7e165813169771628250437a6 Mon Sep 17 00:00:00 2001 From: Ariel Mashraki Date: Tue, 24 May 2022 11:25:03 +0300 Subject: [PATCH] ent: initial support for edge schemas --- dialect/sql/sqlgraph/graph.go | 32 +- dialect/sql/sqlgraph/graph_test.go | 46 + entc/gen/graph.go | 173 +- entc/gen/graph_test.go | 44 +- entc/gen/template/builder/create.tmpl | 13 +- entc/gen/template/builder/mutation.tmpl | 213 +- entc/gen/template/builder/query.tmpl | 124 +- entc/gen/template/builder/setter.tmpl | 3 +- entc/gen/template/builder/update.tmpl | 2 +- entc/gen/template/client.tmpl | 97 +- entc/gen/template/dialect/sql/create.tmpl | 39 +- entc/gen/template/dialect/sql/decode.tmpl | 31 +- entc/gen/template/dialect/sql/delete.tmpl | 10 +- entc/gen/template/dialect/sql/meta.tmpl | 10 +- entc/gen/template/dialect/sql/predicate.tmpl | 34 +- entc/gen/template/dialect/sql/query.tmpl | 50 +- entc/gen/template/dialect/sql/update.tmpl | 62 +- entc/gen/template/ent.tmpl | 25 +- entc/gen/template/import.tmpl | 8 +- entc/gen/template/meta.tmpl | 10 +- entc/gen/template/runtime.tmpl | 2 +- entc/gen/template/where.tmpl | 38 +- entc/gen/type.go | 70 +- entc/integration/cascadelete/ent/client.go | 18 +- entc/integration/cascadelete/ent/comment.go | 7 +- .../cascadelete/ent/comment_create.go | 2 +- entc/integration/cascadelete/ent/post.go | 7 +- .../cascadelete/ent/post_create.go | 2 +- entc/integration/cascadelete/ent/user.go | 4 +- .../cascadelete/ent/user_create.go | 2 +- entc/integration/config/ent/client.go | 6 +- entc/integration/config/ent/user.go | 7 +- entc/integration/config/ent/user_create.go | 2 +- entc/integration/customid/ent/account.go | 4 +- entc/integration/customid/ent/blob.go | 7 +- entc/integration/customid/ent/car.go | 10 +- entc/integration/customid/ent/car_create.go | 2 +- entc/integration/customid/ent/client.go | 84 +- entc/integration/customid/ent/doc.go | 4 +- entc/integration/customid/ent/group_create.go | 2 +- entc/integration/customid/ent/mixinid.go | 7 +- entc/integration/customid/ent/note.go | 4 +- entc/integration/customid/ent/token.go | 4 +- entc/integration/customid/ent/user_create.go | 2 +- entc/integration/edgefield/ent/car.go | 4 +- entc/integration/edgefield/ent/card.go | 7 +- entc/integration/edgefield/ent/card_create.go | 2 +- entc/integration/edgefield/ent/client.go | 54 +- entc/integration/edgefield/ent/info.go | 4 +- entc/integration/edgefield/ent/info_create.go | 2 +- entc/integration/edgefield/ent/metadata.go | 7 +- .../edgefield/ent/metadata_create.go | 2 +- entc/integration/edgefield/ent/node.go | 7 +- entc/integration/edgefield/ent/node_create.go | 2 +- entc/integration/edgefield/ent/pet.go | 4 +- entc/integration/edgefield/ent/pet_create.go | 2 +- entc/integration/edgefield/ent/post.go | 7 +- entc/integration/edgefield/ent/post_create.go | 2 +- entc/integration/edgefield/ent/rental.go | 10 +- .../edgefield/ent/rental_create.go | 2 +- entc/integration/edgefield/ent/user.go | 7 +- entc/integration/edgefield/ent/user_create.go | 2 +- .../integration/edgeschema/edgeschema_test.go | 168 + entc/integration/edgeschema/ent/client.go | 1016 +++++ entc/integration/edgeschema/ent/config.go | 65 + entc/integration/edgeschema/ent/context.go | 33 + entc/integration/edgeschema/ent/ent.go | 478 +++ .../edgeschema/ent/enttest/enttest.go | 78 + entc/integration/edgeschema/ent/friendship.go | 186 + .../edgeschema/ent/friendship/friendship.go | 68 + .../edgeschema/ent/friendship/where.go | 458 ++ .../edgeschema/ent/friendship_create.go | 349 ++ .../edgeschema/ent/friendship_delete.go | 111 + .../edgeschema/ent/friendship_query.go | 658 +++ .../edgeschema/ent/friendship_update.go | 601 +++ entc/integration/edgeschema/ent/generate.go | 7 + entc/integration/edgeschema/ent/group.go | 141 + .../integration/edgeschema/ent/group/group.go | 57 + .../integration/edgeschema/ent/group/where.go | 298 ++ .../edgeschema/ent/group_create.go | 318 ++ .../edgeschema/ent/group_delete.go | 111 + .../integration/edgeschema/ent/group_query.go | 686 +++ .../edgeschema/ent/group_update.go | 673 +++ entc/integration/edgeschema/ent/hook/hook.go | 282 ++ .../edgeschema/ent/migrate/migrate.go | 71 + .../edgeschema/ent/migrate/schema.go | 186 + entc/integration/edgeschema/ent/mutation.go | 3718 +++++++++++++++++ .../edgeschema/ent/predicate/predicate.go | 28 + .../edgeschema/ent/relationship.go | 163 + .../ent/relationship/relationship.go | 58 + .../edgeschema/ent/relationship/where.go | 290 ++ .../edgeschema/ent/relationship_create.go | 306 ++ .../edgeschema/ent/relationship_delete.go | 106 + .../edgeschema/ent/relationship_query.go | 579 +++ .../edgeschema/ent/relationship_update.go | 542 +++ entc/integration/edgeschema/ent/runtime.go | 61 + .../edgeschema/ent/runtime/runtime.go | 9 + .../edgeschema/ent/schema/friendship.go | 44 + .../edgeschema/ent/schema/group.go | 33 + .../edgeschema/ent/schema/relationship.go | 47 + .../edgeschema/ent/schema/tweet.go | 32 + .../edgeschema/ent/schema/tweetlike.go | 49 + .../integration/edgeschema/ent/schema/user.go | 38 + .../edgeschema/ent/schema/usergroup.go | 42 + entc/integration/edgeschema/ent/tweet.go | 141 + .../integration/edgeschema/ent/tweet/tweet.go | 52 + .../integration/edgeschema/ent/tweet/where.go | 298 ++ .../edgeschema/ent/tweet_create.go | 265 ++ .../edgeschema/ent/tweet_delete.go | 111 + .../integration/edgeschema/ent/tweet_query.go | 686 +++ .../edgeschema/ent/tweet_update.go | 476 +++ entc/integration/edgeschema/ent/tweetlike.go | 167 + .../edgeschema/ent/tweetlike/tweetlike.go | 64 + .../edgeschema/ent/tweetlike/where.go | 292 ++ .../edgeschema/ent/tweetlike_create.go | 308 ++ .../edgeschema/ent/tweetlike_delete.go | 106 + .../edgeschema/ent/tweetlike_query.go | 580 +++ .../edgeschema/ent/tweetlike_update.go | 516 +++ entc/integration/edgeschema/ent/tx.go | 228 + entc/integration/edgeschema/ent/user.go | 237 ++ entc/integration/edgeschema/ent/user/user.go | 108 + entc/integration/edgeschema/ent/user/where.go | 466 +++ .../integration/edgeschema/ent/user_create.go | 468 +++ .../integration/edgeschema/ent/user_delete.go | 111 + entc/integration/edgeschema/ent/user_query.go | 1140 +++++ .../integration/edgeschema/ent/user_update.go | 1467 +++++++ entc/integration/edgeschema/ent/usergroup.go | 176 + .../edgeschema/ent/usergroup/usergroup.go | 63 + .../edgeschema/ent/usergroup/where.go | 375 ++ .../edgeschema/ent/usergroup_create.go | 321 ++ .../edgeschema/ent/usergroup_delete.go | 111 + .../edgeschema/ent/usergroup_query.go | 659 +++ .../edgeschema/ent/usergroup_update.go | 532 +++ entc/integration/ent/card.go | 16 +- entc/integration/ent/card_create.go | 2 +- entc/integration/ent/client.go | 84 +- entc/integration/ent/comment.go | 13 +- entc/integration/ent/comment_create.go | 2 +- entc/integration/ent/fieldtype.go | 196 +- entc/integration/ent/fieldtype_create.go | 2 +- entc/integration/ent/file.go | 16 +- entc/integration/ent/file_create.go | 2 +- entc/integration/ent/filetype.go | 10 +- entc/integration/ent/filetype_create.go | 2 +- entc/integration/ent/goods_create.go | 2 +- entc/integration/ent/group.go | 16 +- entc/integration/ent/group_create.go | 2 +- entc/integration/ent/groupinfo.go | 7 +- entc/integration/ent/groupinfo_create.go | 2 +- entc/integration/ent/item.go | 4 +- entc/integration/ent/node.go | 4 +- entc/integration/ent/node_create.go | 2 +- entc/integration/ent/pet.go | 13 +- entc/integration/ent/pet_create.go | 2 +- entc/integration/ent/spec_create.go | 2 +- entc/integration/ent/task.go | 4 +- entc/integration/ent/task_create.go | 2 +- entc/integration/ent/user.go | 34 +- entc/integration/ent/user_create.go | 2 +- entc/integration/gremlin/ent/card.go | 16 +- entc/integration/gremlin/ent/client.go | 84 +- entc/integration/gremlin/ent/comment.go | 13 +- entc/integration/gremlin/ent/fieldtype.go | 196 +- entc/integration/gremlin/ent/file.go | 16 +- entc/integration/gremlin/ent/filetype.go | 10 +- entc/integration/gremlin/ent/group.go | 16 +- entc/integration/gremlin/ent/groupinfo.go | 7 +- entc/integration/gremlin/ent/item.go | 4 +- entc/integration/gremlin/ent/node.go | 4 +- entc/integration/gremlin/ent/pet.go | 13 +- entc/integration/gremlin/ent/task.go | 4 +- entc/integration/gremlin/ent/user.go | 34 +- entc/integration/hooks/ent/card.go | 13 +- entc/integration/hooks/ent/card_create.go | 2 +- entc/integration/hooks/ent/client.go | 12 +- entc/integration/hooks/ent/user.go | 13 +- entc/integration/hooks/ent/user_create.go | 2 +- entc/integration/idtype/ent/client.go | 6 +- entc/integration/idtype/ent/user.go | 4 +- entc/integration/idtype/ent/user_create.go | 2 +- entc/integration/json/ent/client.go | 6 +- entc/integration/json/ent/user.go | 25 +- entc/integration/json/ent/user_create.go | 2 +- entc/integration/migrate/entv1/car_create.go | 2 +- entc/integration/migrate/entv1/client.go | 24 +- entc/integration/migrate/entv1/conversion.go | 28 +- .../migrate/entv1/conversion_create.go | 2 +- entc/integration/migrate/entv1/customtype.go | 4 +- .../migrate/entv1/customtype_create.go | 2 +- entc/integration/migrate/entv1/user.go | 37 +- entc/integration/migrate/entv1/user_create.go | 2 +- entc/integration/migrate/entv2/car.go | 4 +- entc/integration/migrate/entv2/car_create.go | 2 +- entc/integration/migrate/entv2/client.go | 42 +- entc/integration/migrate/entv2/conversion.go | 28 +- .../migrate/entv2/conversion_create.go | 2 +- entc/integration/migrate/entv2/customtype.go | 10 +- .../migrate/entv2/customtype_create.go | 2 +- .../integration/migrate/entv2/group_create.go | 2 +- entc/integration/migrate/entv2/media.go | 10 +- .../integration/migrate/entv2/media_create.go | 2 +- entc/integration/migrate/entv2/pet.go | 4 +- entc/integration/migrate/entv2/pet_create.go | 2 +- entc/integration/migrate/entv2/user.go | 52 +- entc/integration/migrate/entv2/user_create.go | 2 +- entc/integration/migrate/versioned/client.go | 6 +- entc/integration/migrate/versioned/user.go | 13 +- .../migrate/versioned/user_create.go | 2 +- entc/integration/multischema/ent/client.go | 18 +- entc/integration/multischema/ent/group.go | 4 +- .../multischema/ent/group_create.go | 2 +- entc/integration/multischema/ent/pet.go | 7 +- .../integration/multischema/ent/pet_create.go | 2 +- entc/integration/multischema/ent/user.go | 4 +- .../multischema/ent/user_create.go | 2 +- entc/integration/privacy/ent/client.go | 18 +- entc/integration/privacy/ent/task.go | 13 +- entc/integration/privacy/ent/task_create.go | 2 +- entc/integration/privacy/ent/team.go | 4 +- entc/integration/privacy/ent/team_create.go | 2 +- entc/integration/privacy/ent/user.go | 7 +- entc/integration/privacy/ent/user_create.go | 2 +- entc/integration/template/ent/client.go | 18 +- entc/integration/template/ent/group_create.go | 2 +- entc/integration/template/ent/pet_create.go | 2 +- entc/integration/template/ent/user_create.go | 2 +- entc/load/schema.go | 2 + examples/edgeindex/ent/city.go | 4 +- examples/edgeindex/ent/city_create.go | 2 +- examples/edgeindex/ent/client.go | 12 +- examples/edgeindex/ent/street.go | 4 +- examples/edgeindex/ent/street_create.go | 2 +- examples/entcpkg/ent/client.go | 6 +- examples/entcpkg/ent/user.go | 7 +- examples/entcpkg/ent/user_create.go | 2 +- examples/fs/ent/client.go | 6 +- examples/fs/ent/file.go | 10 +- examples/fs/ent/file_create.go | 2 +- examples/m2m2types/ent/client.go | 12 +- examples/m2m2types/ent/group.go | 4 +- examples/m2m2types/ent/group_create.go | 2 +- examples/m2m2types/ent/user.go | 7 +- examples/m2m2types/ent/user_create.go | 2 +- examples/m2mbidi/ent/client.go | 6 +- examples/m2mbidi/ent/user.go | 7 +- examples/m2mbidi/ent/user_create.go | 2 +- examples/m2mrecur/ent/client.go | 6 +- examples/m2mrecur/ent/user.go | 7 +- examples/m2mrecur/ent/user_create.go | 2 +- examples/o2m2types/ent/client.go | 12 +- examples/o2m2types/ent/pet.go | 4 +- examples/o2m2types/ent/pet_create.go | 2 +- examples/o2m2types/ent/user.go | 7 +- examples/o2m2types/ent/user_create.go | 2 +- examples/o2mrecur/ent/client.go | 6 +- examples/o2mrecur/ent/node.go | 4 +- examples/o2mrecur/ent/node_create.go | 2 +- examples/o2o2types/ent/card.go | 7 +- examples/o2o2types/ent/card_create.go | 2 +- examples/o2o2types/ent/client.go | 12 +- examples/o2o2types/ent/user.go | 7 +- examples/o2o2types/ent/user_create.go | 2 +- examples/o2obidi/ent/client.go | 6 +- examples/o2obidi/ent/user.go | 7 +- examples/o2obidi/ent/user_create.go | 2 +- examples/o2orecur/ent/client.go | 6 +- examples/o2orecur/ent/node.go | 4 +- examples/o2orecur/ent/node_create.go | 2 +- examples/privacyadmin/ent/client.go | 6 +- examples/privacyadmin/ent/user.go | 4 +- examples/privacyadmin/ent/user_create.go | 2 +- examples/privacytenant/ent/client.go | 18 +- examples/privacytenant/ent/group.go | 4 +- examples/privacytenant/ent/group_create.go | 2 +- examples/privacytenant/ent/tenant.go | 4 +- examples/privacytenant/ent/tenant_create.go | 2 +- examples/privacytenant/ent/user.go | 7 +- examples/privacytenant/ent/user_create.go | 2 +- examples/start/ent/car.go | 7 +- examples/start/ent/car_create.go | 2 +- examples/start/ent/client.go | 18 +- examples/start/ent/group.go | 4 +- examples/start/ent/group_create.go | 2 +- examples/start/ent/user.go | 7 +- examples/start/ent/user_create.go | 2 +- examples/traversal/ent/client.go | 18 +- examples/traversal/ent/group.go | 4 +- examples/traversal/ent/group_create.go | 2 +- examples/traversal/ent/pet.go | 4 +- examples/traversal/ent/pet_create.go | 2 +- examples/traversal/ent/user.go | 7 +- examples/traversal/ent/user_create.go | 2 +- examples/version/ent/client.go | 6 +- examples/version/ent/user.go | 7 +- examples/version/ent/user_create.go | 2 +- schema/edge/edge.go | 44 +- schema/field/annotation.go | 35 +- 297 files changed, 25772 insertions(+), 1228 deletions(-) create mode 100644 entc/integration/edgeschema/edgeschema_test.go create mode 100644 entc/integration/edgeschema/ent/client.go create mode 100644 entc/integration/edgeschema/ent/config.go create mode 100644 entc/integration/edgeschema/ent/context.go create mode 100644 entc/integration/edgeschema/ent/ent.go create mode 100644 entc/integration/edgeschema/ent/enttest/enttest.go create mode 100644 entc/integration/edgeschema/ent/friendship.go create mode 100644 entc/integration/edgeschema/ent/friendship/friendship.go create mode 100644 entc/integration/edgeschema/ent/friendship/where.go create mode 100644 entc/integration/edgeschema/ent/friendship_create.go create mode 100644 entc/integration/edgeschema/ent/friendship_delete.go create mode 100644 entc/integration/edgeschema/ent/friendship_query.go create mode 100644 entc/integration/edgeschema/ent/friendship_update.go create mode 100644 entc/integration/edgeschema/ent/generate.go create mode 100644 entc/integration/edgeschema/ent/group.go create mode 100644 entc/integration/edgeschema/ent/group/group.go create mode 100644 entc/integration/edgeschema/ent/group/where.go create mode 100644 entc/integration/edgeschema/ent/group_create.go create mode 100644 entc/integration/edgeschema/ent/group_delete.go create mode 100644 entc/integration/edgeschema/ent/group_query.go create mode 100644 entc/integration/edgeschema/ent/group_update.go create mode 100644 entc/integration/edgeschema/ent/hook/hook.go create mode 100644 entc/integration/edgeschema/ent/migrate/migrate.go create mode 100644 entc/integration/edgeschema/ent/migrate/schema.go create mode 100644 entc/integration/edgeschema/ent/mutation.go create mode 100644 entc/integration/edgeschema/ent/predicate/predicate.go create mode 100644 entc/integration/edgeschema/ent/relationship.go create mode 100644 entc/integration/edgeschema/ent/relationship/relationship.go create mode 100644 entc/integration/edgeschema/ent/relationship/where.go create mode 100644 entc/integration/edgeschema/ent/relationship_create.go create mode 100644 entc/integration/edgeschema/ent/relationship_delete.go create mode 100644 entc/integration/edgeschema/ent/relationship_query.go create mode 100644 entc/integration/edgeschema/ent/relationship_update.go create mode 100644 entc/integration/edgeschema/ent/runtime.go create mode 100644 entc/integration/edgeschema/ent/runtime/runtime.go create mode 100644 entc/integration/edgeschema/ent/schema/friendship.go create mode 100644 entc/integration/edgeschema/ent/schema/group.go create mode 100644 entc/integration/edgeschema/ent/schema/relationship.go create mode 100644 entc/integration/edgeschema/ent/schema/tweet.go create mode 100644 entc/integration/edgeschema/ent/schema/tweetlike.go create mode 100644 entc/integration/edgeschema/ent/schema/user.go create mode 100644 entc/integration/edgeschema/ent/schema/usergroup.go create mode 100644 entc/integration/edgeschema/ent/tweet.go create mode 100644 entc/integration/edgeschema/ent/tweet/tweet.go create mode 100644 entc/integration/edgeschema/ent/tweet/where.go create mode 100644 entc/integration/edgeschema/ent/tweet_create.go create mode 100644 entc/integration/edgeschema/ent/tweet_delete.go create mode 100644 entc/integration/edgeschema/ent/tweet_query.go create mode 100644 entc/integration/edgeschema/ent/tweet_update.go create mode 100644 entc/integration/edgeschema/ent/tweetlike.go create mode 100644 entc/integration/edgeschema/ent/tweetlike/tweetlike.go create mode 100644 entc/integration/edgeschema/ent/tweetlike/where.go create mode 100644 entc/integration/edgeschema/ent/tweetlike_create.go create mode 100644 entc/integration/edgeschema/ent/tweetlike_delete.go create mode 100644 entc/integration/edgeschema/ent/tweetlike_query.go create mode 100644 entc/integration/edgeschema/ent/tweetlike_update.go create mode 100644 entc/integration/edgeschema/ent/tx.go create mode 100644 entc/integration/edgeschema/ent/user.go create mode 100644 entc/integration/edgeschema/ent/user/user.go create mode 100644 entc/integration/edgeschema/ent/user/where.go create mode 100644 entc/integration/edgeschema/ent/user_create.go create mode 100644 entc/integration/edgeschema/ent/user_delete.go create mode 100644 entc/integration/edgeschema/ent/user_query.go create mode 100644 entc/integration/edgeschema/ent/user_update.go create mode 100644 entc/integration/edgeschema/ent/usergroup.go create mode 100644 entc/integration/edgeschema/ent/usergroup/usergroup.go create mode 100644 entc/integration/edgeschema/ent/usergroup/where.go create mode 100644 entc/integration/edgeschema/ent/usergroup_create.go create mode 100644 entc/integration/edgeschema/ent/usergroup_delete.go create mode 100644 entc/integration/edgeschema/ent/usergroup_query.go create mode 100644 entc/integration/edgeschema/ent/usergroup_update.go diff --git a/dialect/sql/sqlgraph/graph.go b/dialect/sql/sqlgraph/graph.go index d4f89c80d8..0e52d6b9e3 100644 --- a/dialect/sql/sqlgraph/graph.go +++ b/dialect/sql/sqlgraph/graph.go @@ -302,6 +302,9 @@ type ( EdgeTarget struct { Nodes []driver.Value IDSpec *FieldSpec + // Additional fields can be set on the + // edge join table. Valid for M2M edges. + Fields []*FieldSpec } // EdgeSpec holds the information for updating a field @@ -590,7 +593,7 @@ func (q *query) count(ctx context.Context, drv dialect.Driver) (int, error) { // If no columns were selected in count, // the default selection is by node ids. columns := q.Node.Columns - if len(columns) == 0 { + if len(columns) == 0 && q.Node.ID != nil { columns = append(columns, q.Node.ID.Column) } for i, c := range columns { @@ -873,6 +876,12 @@ func (c *creator) node(ctx context.Context, drv dialect.Driver) error { return err } if err := func() error { + // In case the spec does not contain an ID field, we assume + // we interact with an edge-schema with composite primary key. + if c.ID == nil { + query, args := insert.Query() + return c.tx.Exec(ctx, query, args, nil) + } if err := c.insert(ctx, insert); err != nil { return err } @@ -907,7 +916,7 @@ func (c *creator) setTableColumns(insert *sql.InsertBuilder, edges map[Rel][]*Ed return err } -// insert inserts the node to its table and sets its ID if it was not provided by the user. +// insert a node to its table and sets its ID if it was not provided by the user. func (c *creator) insert(ctx context.Context, insert *sql.InsertBuilder) error { if opts := c.CreateSpec.OnConflict; len(opts) > 0 { insert.OnConflict(opts...) @@ -916,7 +925,7 @@ func (c *creator) insert(ctx context.Context, insert *sql.InsertBuilder) error { // If the id field was provided by the user. if c.ID.Value != nil { insert.Set(c.ID.Column, c.ID.Value) - // In case of "ON CONFLICT", the record may exists in the + // In case of "ON CONFLICT", the record may exist in the // database, and we need to get back the database id field. if len(c.CreateSpec.OnConflict) == 0 { query, args := insert.Query() @@ -1128,8 +1137,17 @@ func (g *graph) addM2MEdges(ctx context.Context, ids []driver.Value, edges EdgeS // The EdgeSpec is the same for all members in a group. tables := edges.GroupTable() for _, table := range edgeKeys(tables) { - edges := tables[table] - insert := g.builder.Insert(table).Columns(edges[0].Columns...) + var ( + edges = tables[table] + columns = edges[0].Columns + values = make([]interface{}, 0, len(edges[0].Target.Fields)) + ) + // Specs are generated equally for all edges from the same type. + for _, f := range edges[0].Target.Fields { + values = append(values, f.Value) + columns = append(columns, f.Column) + } + insert := g.builder.Insert(table).Columns(columns...) if edges[0].Schema != "" { // If the Schema field was provided to the EdgeSpec (by the // generated code), it should be the same for all EdgeSpecs. @@ -1141,9 +1159,9 @@ func (g *graph) addM2MEdges(ctx context.Context, ids []driver.Value, edges EdgeS pk1, pk2 = pk2, pk1 } for _, pair := range product(pk1, pk2) { - insert.Values(pair[0], pair[1]) + insert.Values(append([]interface{}{pair[0], pair[1]}, values...)...) if edge.Bidi { - insert.Values(pair[1], pair[0]) + insert.Values(append([]interface{}{pair[1], pair[0]}, values...)...) } } } diff --git a/dialect/sql/sqlgraph/graph_test.go b/dialect/sql/sqlgraph/graph_test.go index 7389f46b3d..44a1819993 100644 --- a/dialect/sql/sqlgraph/graph_test.go +++ b/dialect/sql/sqlgraph/graph_test.go @@ -1135,6 +1135,29 @@ func TestCreateNode(t *testing.T) { m.ExpectCommit() }, }, + { + name: "edges/m2m/fields", + spec: &CreateSpec{ + Table: "groups", + ID: &FieldSpec{Column: "id", Type: field.TypeInt}, + Fields: []*FieldSpec{ + {Column: "name", Type: field.TypeString, Value: "GitHub"}, + }, + Edges: []*EdgeSpec{ + {Rel: M2M, Table: "group_users", Columns: []string{"group_id", "user_id"}, Target: &EdgeTarget{Nodes: []driver.Value{2}, IDSpec: &FieldSpec{Column: "id"}, Fields: []*FieldSpec{{Column: "ts", Type: field.TypeInt, Value: 3}}}}, + }, + }, + expect: func(m sqlmock.Sqlmock) { + m.ExpectBegin() + m.ExpectExec(escape("INSERT INTO `groups` (`name`) VALUES (?)")). + WithArgs("GitHub"). + WillReturnResult(sqlmock.NewResult(1, 1)) + m.ExpectExec(escape("INSERT INTO `group_users` (`group_id`, `user_id`, `ts`) VALUES (?, ?, ?)")). + WithArgs(1, 2, 3). + WillReturnResult(sqlmock.NewResult(1, 1)) + m.ExpectCommit() + }, + }, { name: "edges/m2m/inverse", spec: &CreateSpec{ @@ -1181,6 +1204,29 @@ func TestCreateNode(t *testing.T) { m.ExpectCommit() }, }, + { + name: "edges/m2m/bidi/fields", + spec: &CreateSpec{ + Table: "users", + ID: &FieldSpec{Column: "id", Type: field.TypeInt}, + Fields: []*FieldSpec{ + {Column: "name", Type: field.TypeString, Value: "mashraki"}, + }, + Edges: []*EdgeSpec{ + {Rel: M2M, Bidi: true, Table: "user_friends", Columns: []string{"user_id", "friend_id"}, Target: &EdgeTarget{Nodes: []driver.Value{2}, IDSpec: &FieldSpec{Column: "id"}, Fields: []*FieldSpec{{Column: "ts", Type: field.TypeInt, Value: 3}}}}, + }, + }, + expect: func(m sqlmock.Sqlmock) { + m.ExpectBegin() + m.ExpectExec(escape("INSERT INTO `users` (`name`) VALUES (?)")). + WithArgs("mashraki"). + WillReturnResult(sqlmock.NewResult(1, 1)) + m.ExpectExec(escape("INSERT INTO `user_friends` (`user_id`, `friend_id`, `ts`) VALUES (?, ?, ?), (?, ?, ?)")). + WithArgs(1, 2, 3, 2, 1, 3). + WillReturnResult(sqlmock.NewResult(1, 1)) + m.ExpectCommit() + }, + }, { name: "edges/m2m/bidi/batch", spec: &CreateSpec{ diff --git a/entc/gen/graph.go b/entc/gen/graph.go index c431dd5d24..6607d082a6 100644 --- a/entc/gen/graph.go +++ b/entc/gen/graph.go @@ -97,6 +97,7 @@ type ( *Config // Nodes are list of Go types that mapped to the types in the loaded schema. Nodes []*Type + nodes map[string]*Type // Schemas holds the raw interfaces for the loaded schemas. Schemas []*load.Schema } @@ -141,7 +142,7 @@ func (f GenerateFunc) Generate(g *Graph) error { // It fails if one of the schemas is invalid. func NewGraph(c *Config, schemas ...*load.Schema) (g *Graph, err error) { defer catch(&err) - g = &Graph{c, make([]*Type, 0, len(schemas)), schemas} + g = &Graph{Config: c, Nodes: make([]*Type, 0, len(schemas)), Schemas: schemas} for i := range schemas { g.addNode(schemas[i]) } @@ -149,11 +150,12 @@ func NewGraph(c *Config, schemas ...*load.Schema) (g *Graph, err error) { g.addEdges(schemas[i]) } for _, t := range g.Nodes { - check(resolve(t), "resolve %q relations", t.Name) + check(g.resolve(t), "resolve %q relations", t.Name) } for _, t := range g.Nodes { check(t.setupFKs(), "set %q foreign-keys", t.Name) } + check(g.edgeSchemas(), "resolving edges") for i := range schemas { g.addIndexes(schemas[i]) } @@ -274,7 +276,7 @@ func (g *Graph) addEdges(schema *load.Schema) { typ, ok := g.typ(e.Type) expect(ok, "type %q does not exist for edge", e.Type) _, ok = t.fields[e.Name] - expect(!ok, "%s schema can't contain field and edge with the same name %q", schema.Name, e.Name) + expect(!ok, "%s schema cannot contain field and edge with the same name %q", schema.Name, e.Name) _, ok = seen[e.Name] expect(!ok, "%s schema contains multiple %q edges", schema.Name, e.Name) seen[e.Name] = struct{}{} @@ -293,7 +295,7 @@ func (g *Graph) addEdges(schema *load.Schema) { }) // Inverse only. case e.Inverse && e.Ref == nil: - expect(e.RefName != "", "missing reference name for inverse edge: %s.%s", t.Name, e.Name) + expect(e.RefName != "", "back-reference edge %s.%s is missing the Ref attribute", t.Name, e.Name) t.Edges = append(t.Edges, &Edge{ def: e, Type: typ, @@ -362,7 +364,7 @@ func (g *Graph) addEdges(schema *load.Schema) { // - A have an edge (E) to B (not unique), and B have a back-reference non-unique edge (E') for E. // - A have an edge (E) to A (not unique). // -func resolve(t *Type) error { +func (g *Graph) resolve(t *Type) error { for _, e := range t.Edges { switch { case e.IsInverse(): @@ -398,8 +400,8 @@ func resolve(t *Type) error { e.Rel.Type, ref.Rel.Type = M2M, M2M table = e.Type.Label() + "_" + ref.Name c1, c2 := ref.Owner.Label()+"_id", ref.Type.Label()+"_id" - // If the relation is from the same type: User has Friends ([]User). - // give the second column a different name (the relation name). + // If the relation is from the same type: User has Friends ([]User), + // we give the second column a different name (the relation name). if c1 == c2 { c2 = rules.Singularize(e.Name) + "_id" } @@ -438,13 +440,131 @@ func resolve(t *Type) error { return nil } +// edgeSchemas visits all edges in the graph and detects which schemas are used as "edge schemas". +// Note, edge schemas cannot be used by more than one association (edge.To), must define two required +// edges (+ edge-fields) to the types that go through them, and allow adding additional fields with +// optional default values. +func (g *Graph) edgeSchemas() error { + for _, n := range g.Nodes { + for _, e := range n.Edges { + if e.def.Through == nil { + continue + } + if !e.M2M() { + return fmt.Errorf("edge %s.%s Through(%q, %s.Type) is allowed only on M2M edges, but got: %q", n.Name, e.Name, e.def.Through.N, e.def.Through.T, e.Rel.Type) + } + typ, ok := g.typ(e.def.Through.T) + switch { + case !ok: + return fmt.Errorf("edge %s.%s defined with Through(%q, %s.Type), but type %[4]s was not found", n.Name, e.Name, e.def.Through.N, e.def.Through.T, e.def.Through.T) + case typ == n: + return fmt.Errorf("edge %s.%s defined with Through(%q, %s.Type), but edge cannot go through itself", n.Name, e.Name, e.def.Through.N, e.def.Through.T) + case e.def.Through.N == "" || n.hasEdge(e.def.Through.N): + return fmt.Errorf("edge %s.%s defined with Through(%q, %s.Type), but schema %[1]s already has an edge named %[3]s", n.Name, e.Name, e.def.Through.N, e.def.Through.T) + case e.IsInverse(): + if typ.EdgeSchema.From != nil { + return fmt.Errorf("type %s is already used as an edge schema by other edge.From: %s.%s", typ.Name, typ.EdgeSchema.From.Name, typ.EdgeSchema.From.Owner.Name) + } + e.Through = typ + typ.EdgeSchema.From = e + if to, from := typ.EdgeSchema.To, typ.EdgeSchema.From; to != nil && from.Ref != to { + return fmt.Errorf("mismtached edge.From(%q, %s.Type) and edge.To(%q, %s.Type) for edge schema %s", from.Name, from.Type.Name, to.Name, to.Type.Name, typ.Name) + } + default: // Assoc. + if typ.EdgeSchema.To != nil { + return fmt.Errorf("type %s is already used as an edge schema by other edge.To: %s.%s", typ.Name, typ.EdgeSchema.From.Name, typ.EdgeSchema.From.Owner.Name) + } + e.Through = typ + typ.EdgeSchema.To = e + if to, from := typ.EdgeSchema.To, typ.EdgeSchema.From; from != nil && from.Ref != to { + return fmt.Errorf("mismtached edge.To(%q, %s.Type) and edge.From(%q, %s.Type) for edge schema %s", from.Name, from.Type.Name, to.Name, to.Type.Name, typ.Name) + } + } + e.Rel.Table = typ.Table() + var ref *Edge + for i, c := range e.Rel.Columns { + r, ok := func() (*Edge, bool) { + for _, fk := range typ.ForeignKeys { + if fk.Field.Name == c { + return fk.Edge, true + } + } + return nil, false + }() + if !ok { + return fmt.Errorf("missing edge-field %s.%s for edge schema used by %s.%s in Through(%q, %s.Type)", typ.Name, c, n.Name, e.Name, e.def.Through.N, typ.Name) + } + if r.Optional { + return fmt.Errorf("edge-schema %s is missing a Required() attribute for its reference edge %q", typ.Name, e.Name) + } + if !e.IsInverse() && i == 0 || e.IsInverse() && i == 1 { + ref = r + } + } + // Edges from src/dest table are always O2M. One row to many + // rows in the join table. Hence, a many-to-many relationship. + n.Edges = append(n.Edges, &Edge{ + def: &load.Edge{}, + Name: e.def.Through.N, + Type: typ, + Inverse: ref.Name, + Ref: ref, + Owner: n, + Optional: true, + StructTag: structTag(e.def.Through.N, ""), + Rel: Relation{ + Type: O2M, + fk: ref.Rel.fk, + Table: ref.Rel.Table, + Columns: ref.Rel.Columns, + }, + }) + // Edge schema contains a composite primary key. + if ant := fieldAnnotate(typ.Annotations); ant != nil && len(ant.ID) > 0 && len(typ.EdgeSchema.ID) == 0 { + r1, r2 := e.Rel.Columns[0], e.Rel.Columns[1] + if len(ant.ID) != 2 || ant.ID[0] != r1 || ant.ID[1] != r2 { + return fmt.Errorf(`edge schema primary key can only be defined on "id" or (%q, %q) in the same order`, r1, r2) + } + typ.ID = nil + for _, f := range ant.ID { + typ.EdgeSchema.ID = append(typ.EdgeSchema.ID, typ.fields[f]) + } + } + if typ.HasCompositeID() { + continue + } + hasI := func() bool { + for _, idx := range typ.Indexes { + if !idx.Unique && len(idx.Columns) != 2 { + continue + } + c1, c2 := idx.Columns[0], idx.Columns[1] + r1, r2 := e.Rel.Columns[0], e.Rel.Columns[1] + if c1 == r1 && c2 == r2 || c1 == r2 && c2 == r1 { + return true + } + } + return false + }() + if !hasI { + if err := typ.AddIndex(&load.Index{Unique: true, Fields: e.Rel.Columns}); err != nil { + return err + } + } + } + } + return nil +} + // Tables returns the schema definitions of SQL tables for the graph. func (g *Graph) Tables() (all []*schema.Table, err error) { tables := make(map[string]*schema.Table) for _, n := range g.Nodes { - table := schema.NewTable(n.Table()). - AddPrimary(n.ID.PK()). - SetAnnotation(n.EntSQL()) + table := schema.NewTable(n.Table()) + if n.HasOneFieldID() { + table.AddPrimary(n.ID.PK()) + } + table.SetAnnotation(n.EntSQL()) for _, f := range n.Fields { if !f.IsEdgeField() { table.AddColumn(f.Column()) @@ -454,7 +574,7 @@ func (g *Graph) Tables() (all []*schema.Table, err error) { all = append(all, table) } for _, n := range g.Nodes { - // Foreign key and a reference, or a join table. + // Foreign key and its reference, or a join table. for _, e := range n.Edges { if e.IsInverse() { continue @@ -497,6 +617,10 @@ func (g *Graph) Tables() (all []*schema.Table, err error) { Symbol: fkSymbol(e, owner, ref), }) case M2M: + // If there is an edge schema for the association (i.e. edge.Through). + if e.Through != nil || e.Ref != nil && e.Ref.Through != nil { + continue + } t1, t2 := tables[n.Table()], tables[e.Type.Table()] c1 := &schema.Column{Name: e.Rel.Columns[0], Type: field.TypeInt} if ref := n.ID; ref.UserDefined { @@ -532,6 +656,9 @@ func (g *Graph) Tables() (all []*schema.Table, err error) { }) } } + if n.HasCompositeID() { + addCompositePK(tables[n.Table()], n) + } } // Append indexes to tables after all columns were added (including relation columns). for _, n := range g.Nodes { @@ -546,13 +673,25 @@ func (g *Graph) Tables() (all []*schema.Table, err error) { return } -// mayAddColumn adds the given column if it doesn't already exist in the table. +// mayAddColumn adds the given column if it does not already exist in the table. func mayAddColumn(t *schema.Table, c *schema.Column) { if !t.HasColumn(c.Name) { t.AddColumn(c) } } +func addCompositePK(t *schema.Table, n *Type) { + columns := make([]*schema.Column, 0, len(n.EdgeSchema.ID)) + for _, id := range n.EdgeSchema.ID { + for i, f := range n.Fields { + if f.IsEdgeField() && id == f && t.Columns[i].Name == f.StorageKey() { + columns = append(columns, t.Columns[i]) + } + } + } + t.PrimaryKey = columns +} + // fkSymbol returns the symbol of the foreign-key constraint for edges of type O2M, M2O and O2O. // It returns the symbol of the storage-key if it was provided, and generate custom one otherwise. func fkSymbol(e *Edge, ownerT, refT *schema.Table) string { @@ -624,12 +763,14 @@ func (g *Graph) SchemaSnapshot() (string, error) { } func (g *Graph) typ(name string) (*Type, bool) { - for _, n := range g.Nodes { - if name == n.Name { - return n, true + if g.nodes == nil { + g.nodes = make(map[string]*Type, len(g.Nodes)) + for _, n := range g.Nodes { + g.nodes[n.Name] = n } } - return nil, false + n, ok := g.nodes[name] + return n, ok } // templates returns the Template to execute on the Graph, diff --git a/entc/gen/graph_test.go b/entc/gen/graph_test.go index 16152f5ccb..100c5a059e 100644 --- a/entc/gen/graph_test.go +++ b/entc/gen/graph_test.go @@ -212,7 +212,49 @@ func TestNewGraphDuplicateEdgeField(t *testing.T) { {Name: "parent", Type: "User"}, }, }) - require.EqualError(t, err, `entc/gen: User schema can't contain field and edge with the same name "parent"`) + require.EqualError(t, err, `entc/gen: User schema cannot contain field and edge with the same name "parent"`) +} + +func TestNewGraphThroughUndefinedType(t *testing.T) { + _, err := NewGraph(&Config{Package: "entc/gen", Storage: drivers[0]}, &load.Schema{ + Name: "T1", + Edges: []*load.Edge{ + {Name: "groups", Type: "T1", Required: true, Through: &struct{ N, T string }{N: "groups_edge", T: "T2"}}, + }, + }) + require.EqualError(t, err, `entc/gen: resolving edges: edge T1.groups defined with Through("groups_edge", T2.Type), but type T2 was not found`) +} + +func TestNewGraphThroughInvalidRel(t *testing.T) { + _, err := NewGraph(&Config{Package: "entc/gen", Storage: drivers[0]}, &load.Schema{ + Name: "T1", + Edges: []*load.Edge{ + {Name: "groups", Type: "T1", Unique: true, Required: true, Through: &struct{ N, T string }{N: "groups_edge", T: "T2"}}, + }, + }) + require.EqualError(t, err, `entc/gen: resolving edges: edge T1.groups Through("groups_edge", T2.Type) is allowed only on M2M edges, but got: "O2O"`) +} + +func TestNewGraphThroughDuplicates(t *testing.T) { + _, err := NewGraph(&Config{Package: "entc/gen", Storage: drivers[0]}, + &load.Schema{ + Name: "User", + Edges: []*load.Edge{ + {Name: "groups", Type: "Group", Through: &struct{ N, T string }{N: "group_edges", T: "T1"}}, + {Name: "group_edges", Type: "Group"}, + }, + }, + &load.Schema{ + Name: "Group", + Edges: []*load.Edge{ + {Name: "users", Type: "User", Inverse: true, RefName: "groups", Through: &struct{ N, T string }{N: "user_edges", T: "T1"}}, + }, + }, + &load.Schema{ + Name: "T1", + }, + ) + require.EqualError(t, err, `entc/gen: resolving edges: edge User.groups defined with Through("group_edges", T1.Type), but schema User already has an edge named group_edges`) } func TestRelation(t *testing.T) { diff --git a/entc/gen/template/builder/create.tmpl b/entc/gen/template/builder/create.tmpl index 7b023b2012..455262ecd4 100644 --- a/entc/gen/template/builder/create.tmpl +++ b/entc/gen/template/builder/create.tmpl @@ -73,8 +73,10 @@ func ({{ $receiver }} *{{ $builder }}) Save(ctx context.Context) (*{{ $.Name }}, if node, err = {{ $receiver }}.{{ $.Storage }}Save(ctx) ; err != nil { return nil, err } - mutation.{{ $.ID.BuilderField }} = &node.{{ $.ID.StructField }} - mutation.done = true + {{- if $.HasOneFieldID }} + mutation.{{ $.ID.BuilderField }} = &node.{{ $.ID.StructField }} + mutation.done = true + {{- end }} return node, err }) for i := len({{ $receiver }}.hooks) - 1; i >= 0; i-- { @@ -118,7 +120,7 @@ func ({{ $receiver }} *{{ $builder }}) ExecX(ctx context.Context) { } } -{{- $fields := $.Fields }}{{ if $.ID.UserDefined }}{{ $fields = append $fields $.ID }}{{ end }} +{{- $fields := $.Fields }}{{ if $.HasOneFieldID }}{{ if $.ID.UserDefined }}{{ $fields = append $fields $.ID }}{{ end }}{{ end }} {{ if $.HasDefault }} // defaults sets the default values of the builder before save. func ({{ $receiver }} *{{ $builder }}) defaults() {{ if $runtimeRequired }}error{{ end }}{ @@ -144,7 +146,8 @@ func ({{ $receiver }} *{{ $builder }}) ExecX(ctx context.Context) { // check runs all checks and user-defined validators on the builder. func ({{ $receiver }} *{{ $builder }}) check() error { {{- range $f := $fields }} - {{- if and (not $f.Optional) (ne $f.Name $.ID.Name) }} + {{- $skip := false }}{{ if $.HasOneFieldID }}{{ if eq $f.Name $.ID.Name }}{{ $skip = true }}{{ end }}{{ end }} + {{- if and (not $f.Optional) (not $skip) }} if _, ok := {{ $mutation }}.{{ $f.MutationGet }}(); !ok { return &ValidationError{Name: "{{ $f.Name }}", err: errors.New(`{{ $pkg }}: missing required field "{{ $.Name }}.{{ $f.Name }}"`)} } @@ -158,7 +161,7 @@ func ({{ $receiver }} *{{ $builder }}) check() error { } {{- end }} {{- end }} - {{- range $e := $.Edges }} + {{- range $e := $.EdgesWithID }} {{- if not $e.Optional }} {{- if $e.Unique }} if _, ok := {{ $mutation }}.{{ $e.StructField }}ID(); !ok { diff --git a/entc/gen/template/builder/mutation.tmpl b/entc/gen/template/builder/mutation.tmpl index 9f719b9a33..656e7ed949 100644 --- a/entc/gen/template/builder/mutation.tmpl +++ b/entc/gen/template/builder/mutation.tmpl @@ -46,7 +46,9 @@ type {{ $mutation }} struct { config op Op typ string - {{ $n.ID.BuilderField }} *{{ $n.ID.Type }} + {{- with $n.HasOneFieldID }} + {{ $n.ID.BuilderField }} *{{ $n.ID.Type }} + {{- end }} {{- range $f := $n.MutationFields }} {{ $f.BuilderField }} *{{ $f.Type }} {{- if $f.SupportsMutationAdd }} @@ -54,7 +56,7 @@ type {{ $mutation }} struct { {{- end }} {{- end }} clearedFields map[string]struct{} - {{- range $e := $n.Edges }} + {{- range $e := $n.EdgesWithID }} {{- if $e.Unique }} {{ $e.BuilderField }} *{{ $e.Type.ID.Type }} {{- else }} @@ -88,39 +90,41 @@ func new{{ $mutation }}(c config, op Op, opts ...{{ $mutationOption }}) *{{ $mut return m } -{{ $opt := print "with" $n.Name "ID" }} -// {{ $opt }} sets the ID field of the mutation. -func {{ $opt }}(id {{ $n.ID.Type }}) {{ $mutationOption }} { - return func(m *{{ $mutation }}) { - var ( - err error - once sync.Once - value *{{ $n.Name }} - ) - m.oldValue = func(ctx context.Context) (*{{ $n.Name }}, error) { - once.Do(func() { - if m.done { - err = errors.New("querying old values post mutation is not allowed") - } else { - value, err = m.Client().{{ $n.Name }}.Get(ctx, id) - } - }) - return value, err +{{ with $n.HasOneFieldID }} + {{ $opt := print "with" $n.Name "ID" }} + // {{ $opt }} sets the ID field of the mutation. + func {{ $opt }}(id {{ $n.ID.Type }}) {{ $mutationOption }} { + return func(m *{{ $mutation }}) { + var ( + err error + once sync.Once + value *{{ $n.Name }} + ) + m.oldValue = func(ctx context.Context) (*{{ $n.Name }}, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().{{ $n.Name }}.Get(ctx, id) + } + }) + return value, err + } + m.{{ $n.ID.BuilderField }} = &id } - m.{{ $n.ID.BuilderField }} = &id } -} -{{ $opt = print "with" $n.Name }} -// {{ $opt }} sets the old {{ $n.Name }} of the mutation. -func {{ $opt }}(node *{{ $n.Name }}) {{ $mutationOption }} { - return func(m *{{ $mutation }}) { - m.oldValue = func(context.Context) (*{{ $n.Name }}, error) { - return node, nil + {{ $opt = print "with" $n.Name }} + // {{ $opt }} sets the old {{ $n.Name }} of the mutation. + func {{ $opt }}(node *{{ $n.Name }}) {{ $mutationOption }} { + return func(m *{{ $mutation }}) { + m.oldValue = func(context.Context) (*{{ $n.Name }}, error) { + return node, nil + } + m.{{ $n.ID.BuilderField }} = &node.ID } - m.{{ $n.ID.BuilderField }} = &node.ID } -} +{{ end }} // Client returns a new `ent.Client` from the mutation. If the mutation was // executed in a transaction (ent.Tx), a transactional client is returned. @@ -141,42 +145,43 @@ func (m {{ $mutation }}) Tx() (*Tx, error) { return tx, nil } -{{- if $n.ID.UserDefined }} - // SetID sets the value of the id field. Note that this - // operation is only accepted on creation of {{ $n.Name }} entities. - func (m *{{ $mutation }}) SetID(id {{ $n.ID.Type }}) { - m.{{ $n.ID.BuilderField }} = &id - } -{{- end }} +{{ with $n.HasOneFieldID }} + {{ if $n.ID.UserDefined }} + // SetID sets the value of the id field. Note that this + // operation is only accepted on creation of {{ $n.Name }} entities. + func (m *{{ $mutation }}) SetID(id {{ $n.ID.Type }}) { + m.{{ $n.ID.BuilderField }} = &id + } + {{ end }} -// 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 *{{ $mutation }}) ID() (id {{ $n.ID.Type }}, exists bool) { - if m.{{ $n.ID.BuilderField }} == nil { - return + // 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 *{{ $mutation }}) ID() (id {{ $n.ID.Type }}, exists bool) { + if m.{{ $n.ID.BuilderField }} == nil { + return + } + return *m.{{ $n.ID.BuilderField }}, true } - return *m.{{ $n.ID.BuilderField }}, 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 *{{ $mutation }}) IDs(ctx context.Context) ([]{{ $n.ID.Type }}, error) { - switch { - case m.op.Is(OpUpdateOne | OpDeleteOne): - id, exists := m.ID() - if exists { - return []{{ $n.ID.Type }}{id}, nil + // 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 *{{ $mutation }}) IDs(ctx context.Context) ([]{{ $n.ID.Type }}, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []{{ $n.ID.Type }}{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().{{ $n.Name }}.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) } - fallthrough - case m.op.Is(OpUpdate | OpDelete): - return m.Client().{{ $n.Name }}.Query().Where(m.predicates...).IDs(ctx) - default: - return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) } -} - +{{ end }} {{ range $f := $n.Fields }} {{ $const := print $n.Package "." $f.Constant }} @@ -200,22 +205,24 @@ func (m *{{ $mutation }}) IDs(ctx context.Context) ([]{{ $n.ID.Type }}, error) { return *v, true } - // {{ $f.MutationGetOld }} returns the old "{{ $f.Name }}" field's value of the {{ $n.Name }} entity. - // If the {{ $n.Name }} 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 *{{ $mutation }}) {{ $f.MutationGetOld }}(ctx context.Context) (v {{ if $f.NillableValue }}*{{ end }}{{ $f.Type }}, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("{{ $f.MutationGetOld }} is only allowed on UpdateOne operations") - } - if m.{{ $n.ID.BuilderField }} == nil || m.oldValue == nil { - return v, errors.New("{{ $f.MutationGetOld }} requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for {{ $f.MutationGetOld }}: %w", err) + {{ if $n.HasOneFieldID }} + // {{ $f.MutationGetOld }} returns the old "{{ $f.Name }}" field's value of the {{ $n.Name }} entity. + // If the {{ $n.Name }} 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 *{{ $mutation }}) {{ $f.MutationGetOld }}(ctx context.Context) (v {{ if $f.NillableValue }}*{{ end }}{{ $f.Type }}, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("{{ $f.MutationGetOld }} is only allowed on UpdateOne operations") + } + if m.{{ $n.ID.BuilderField }} == nil || m.oldValue == nil { + return v, errors.New("{{ $f.MutationGetOld }} requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for {{ $f.MutationGetOld }}: %w", err) + } + return oldValue.{{ $f.StructField }}, nil } - return oldValue.{{ $f.StructField }}, nil - } + {{ end }} {{ if $f.SupportsMutationAdd }} {{ $func := print "Add" $f.StructField }} @@ -272,7 +279,7 @@ func (m *{{ $mutation }}) IDs(ctx context.Context) ([]{{ $n.ID.Type }}, error) { {{ end }} -{{ range $e := $n.Edges }} +{{ range $e := $n.EdgesWithID }} {{ $op := "add" }}{{ $idsFunc := $e.MutationAdd }}{{ if $e.Unique }}{{ $op = "set" }}{{ $idsFunc = $e.MutationSet }}{{ end }} {{/* Check if this setter was already defined by the field-setters (e.g. edge-field with the same name). */}} {{ $withSetGet := not $e.HasFieldSetter }} @@ -416,16 +423,20 @@ func (m *{{ $mutation }}) Field(name string) (ent.Value, bool) { // returned if the mutation operation is not UpdateOne, or the query to the // database failed. func (m *{{ $mutation }}) OldField(ctx context.Context, name string) (ent.Value, error) { - {{- with $n.Fields }} - switch name { - {{- range $f := . }} - {{- $const := print $n.Package "." $f.Constant }} - case {{ $const }}: - return m.{{ $f.MutationGetOld }}(ctx) + {{- if $n.HasCompositeID }} + return nil, errors.New("edge schema {{ $n.Name }} does not support getting old values") + {{- else }} + {{- with $n.Fields }} + switch name { + {{- range $f := . }} + {{- $const := print $n.Package "." $f.Constant }} + case {{ $const }}: + return m.{{ $f.MutationGetOld }}(ctx) + {{- end }} + } {{- end }} - } + return nil, fmt.Errorf("unknown {{ $n.Name }} field %s", name) {{- end }} - return nil, fmt.Errorf("unknown {{ $n.Name }} field %s", name) } // SetField sets the value of a field with the given name. It returns an error if @@ -570,8 +581,8 @@ func (m *{{ $mutation }}) ResetField(name string) error { // AddedEdges returns all edge names that were set/added in this mutation. func (m *{{ $mutation }}) AddedEdges() []string { - edges := make([]string, 0, {{ len $n.Edges }}) - {{- range $e := $n.Edges }} + edges := make([]string, 0, {{ len $n.EdgesWithID }}) + {{- range $e := $n.EdgesWithID }} if m.{{ $e.BuilderField }} != nil { {{- $const := print $n.Package "." $e.Constant }} edges = append(edges, {{ $const }}) @@ -583,9 +594,9 @@ func (m *{{ $mutation }}) AddedEdges() []string { // AddedIDs returns all IDs (to other nodes) that were added for the given edge // name in this mutation. func (m *{{ $mutation }}) AddedIDs(name string) []ent.Value { - {{- with $n.Edges }} + {{- with $n.EdgesWithID }} switch name { - {{- range $e := $n.Edges }} + {{- range $e := $n.EdgesWithID }} {{- $const := print $n.Package "." $e.Constant }} case {{ $const }}: {{- if $e.Unique }} @@ -607,8 +618,8 @@ func (m *{{ $mutation }}) AddedIDs(name string) []ent.Value { // RemovedEdges returns all edge names that were removed in this mutation. func (m *{{ $mutation }}) RemovedEdges() []string { - edges := make([]string, 0, {{ len $n.Edges }}) - {{- range $e := $n.Edges }} + edges := make([]string, 0, {{ len $n.EdgesWithID }}) + {{- range $e := $n.EdgesWithID }} {{- if not $e.Unique }} if m.removed{{ $e.BuilderField }} != nil { {{- $const := print $n.Package "." $e.Constant }} @@ -622,9 +633,9 @@ func (m *{{ $mutation }}) RemovedEdges() []string { // RemovedIDs returns all IDs (to other nodes) that were removed for the edge with // the given name in this mutation. func (m *{{ $mutation }}) RemovedIDs(name string) []ent.Value { - {{- with $n.Edges }} + {{- with $n.EdgesWithID }} switch name { - {{- range $e := $n.Edges }} + {{- range $e := $n.EdgesWithID }} {{- if not $e.Unique }} {{- $const := print $n.Package "." $e.Constant }} case {{ $const }}: @@ -642,8 +653,8 @@ func (m *{{ $mutation }}) RemovedIDs(name string) []ent.Value { // ClearedEdges returns all edge names that were cleared in this mutation. func (m *{{ $mutation }}) ClearedEdges() []string { - edges := make([]string, 0, {{ len $n.Edges }}) - {{- range $e := $n.Edges }} + edges := make([]string, 0, {{ len $n.EdgesWithID }}) + {{- range $e := $n.EdgesWithID }} if m.cleared{{ $e.BuilderField }} { {{- $const := print $n.Package "." $e.Constant }} edges = append(edges, {{ $const }}) @@ -655,9 +666,9 @@ func (m *{{ $mutation }}) ClearedEdges() []string { // EdgeCleared returns a boolean which indicates if the edge with the given name // was cleared in this mutation. func (m *{{ $mutation }}) EdgeCleared(name string) bool { - {{- with $n.Edges }} + {{- with $n.EdgesWithID }} switch name { - {{- range $e := $n.Edges }} + {{- range $e := $n.EdgesWithID }} {{- $const := print $n.Package "." $e.Constant }} case {{ $const }}: return m.cleared{{ $e.BuilderField }} @@ -670,9 +681,9 @@ func (m *{{ $mutation }}) EdgeCleared(name string) bool { // 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 *{{ $mutation }}) ClearEdge(name string) error { - {{- with $n.Edges }} + {{- with $n.EdgesWithID }} switch name { - {{- range $e := $n.Edges }} + {{- range $e := $n.EdgesWithID }} {{- if $e.Unique }} {{- $const := print $n.Package "." $e.Constant }} case {{ $const }}: @@ -688,9 +699,9 @@ func (m *{{ $mutation }}) ClearEdge(name string) error { // 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 *{{ $mutation }}) ResetEdge(name string) error { - {{- with $n.Edges }} + {{- with $n.EdgesWithID }} switch name { - {{- range $e := $n.Edges }} + {{- range $e := $n.EdgesWithID }} {{- $const := print $n.Package "." $e.Constant }} case {{ $const }}: m.{{ $e.MutationReset }}() diff --git a/entc/gen/template/builder/query.tmpl b/entc/gen/template/builder/query.tmpl index 68fa4c7e30..c651854af3 100644 --- a/entc/gen/template/builder/query.tmpl +++ b/entc/gen/template/builder/query.tmpl @@ -120,28 +120,30 @@ func ({{ $receiver }} *{{ $builder }}) FirstX(ctx context.Context) *{{ $.Name }} return node } -// FirstID returns the first {{ $.Name }} ID from the query. -// Returns a *NotFoundError when no {{ $.Name }} ID was found. -func ({{ $receiver }} *{{ $builder }}) FirstID(ctx context.Context) (id {{ $.ID.Type }}, err error) { - var ids []{{ $.ID.Type }} - if ids, err = {{ $receiver }}.Limit(1).IDs(ctx); err != nil { - return - } - if len(ids) == 0 { - err = &NotFoundError{ {{ $.Package }}.Label} - return +{{ if $.HasOneFieldID }} + // FirstID returns the first {{ $.Name }} ID from the query. + // Returns a *NotFoundError when no {{ $.Name }} ID was found. + func ({{ $receiver }} *{{ $builder }}) FirstID(ctx context.Context) (id {{ $.ID.Type }}, err error) { + var ids []{{ $.ID.Type }} + if ids, err = {{ $receiver }}.Limit(1).IDs(ctx); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{ {{ $.Package }}.Label} + return + } + return ids[0], nil } - return ids[0], nil -} - -// FirstIDX is like FirstID, but panics if an error occurs. -func ({{ $receiver }} *{{ $builder }}) FirstIDX(ctx context.Context) {{ $.ID.Type }} { - id, err := {{ $receiver }}.FirstID(ctx) - if err != nil && !IsNotFound(err) { - panic(err) + + // FirstIDX is like FirstID, but panics if an error occurs. + func ({{ $receiver }} *{{ $builder }}) FirstIDX(ctx context.Context) {{ $.ID.Type }} { + id, err := {{ $receiver }}.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id } - return id -} +{{ end }} // Only returns a single {{ $.Name }} entity found by the query, ensuring it only returns one. // Returns a *NotSingularError when more than one {{ $.Name }} entity is found. @@ -170,33 +172,35 @@ func ({{ $receiver }} *{{ $builder }}) OnlyX(ctx context.Context) *{{ $.Name }} return node } -// OnlyID is like Only, but returns the only {{ $.Name }} ID in the query. -// Returns a *NotSingularError when more than one {{ $.Name }} ID is found. -// Returns a *NotFoundError when no entities are found. -func ({{ $receiver }} *{{ $builder }}) OnlyID(ctx context.Context) (id {{ $.ID.Type }}, err error) { - var ids []{{ $.ID.Type }} - if ids, err = {{ $receiver }}.Limit(2).IDs(ctx); err != nil { +{{ if $.HasOneFieldID }} + // OnlyID is like Only, but returns the only {{ $.Name }} ID in the query. + // Returns a *NotSingularError when more than one {{ $.Name }} ID is found. + // Returns a *NotFoundError when no entities are found. + func ({{ $receiver }} *{{ $builder }}) OnlyID(ctx context.Context) (id {{ $.ID.Type }}, err error) { + var ids []{{ $.ID.Type }} + if ids, err = {{ $receiver }}.Limit(2).IDs(ctx); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{ {{ $.Package }}.Label} + default: + err = &NotSingularError{ {{ $.Package }}.Label} + } return } - switch len(ids) { - case 1: - id = ids[0] - case 0: - err = &NotFoundError{ {{ $.Package }}.Label} - default: - err = &NotSingularError{ {{ $.Package }}.Label} - } - return -} - -// OnlyIDX is like OnlyID, but panics if an error occurs. -func ({{ $receiver }} *{{ $builder }}) OnlyIDX(ctx context.Context) {{ $.ID.Type }} { - id, err := {{ $receiver }}.OnlyID(ctx) - if err != nil { - panic(err) + + // OnlyIDX is like OnlyID, but panics if an error occurs. + func ({{ $receiver }} *{{ $builder }}) OnlyIDX(ctx context.Context) {{ $.ID.Type }} { + id, err := {{ $receiver }}.OnlyID(ctx) + if err != nil { + panic(err) + } + return id } - return id -} +{{ end }} // All executes the query and returns a list of {{ plural $.Name }}. func ({{ $receiver }} *{{ $builder }}) All(ctx context.Context) ([]*{{ $.Name }}, error) { @@ -215,23 +219,25 @@ func ({{ $receiver }} *{{ $builder }}) AllX(ctx context.Context) []*{{ $.Name }} return nodes } -// IDs executes the query and returns a list of {{ $.Name }} IDs. -func ({{ $receiver }} *{{ $builder }}) IDs(ctx context.Context) ([]{{ $.ID.Type }}, error) { - var ids []{{ $.ID.Type }} - if err := {{ $receiver }}.Select({{ $.Package }}.FieldID).Scan(ctx, &ids); err != nil { - return nil, err +{{ if $.HasOneFieldID }} + // IDs executes the query and returns a list of {{ $.Name }} IDs. + func ({{ $receiver }} *{{ $builder }}) IDs(ctx context.Context) ([]{{ $.ID.Type }}, error) { + var ids []{{ $.ID.Type }} + if err := {{ $receiver }}.Select({{ $.Package }}.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil } - return ids, nil -} - -// IDsX is like IDs, but panics if an error occurs. -func ({{ $receiver }} *{{ $builder }}) IDsX(ctx context.Context) []{{ $.ID.Type }} { - ids, err := {{ $receiver }}.IDs(ctx) - if err != nil { - panic(err) + + // IDsX is like IDs, but panics if an error occurs. + func ({{ $receiver }} *{{ $builder }}) IDsX(ctx context.Context) []{{ $.ID.Type }} { + ids, err := {{ $receiver }}.IDs(ctx) + if err != nil { + panic(err) + } + return ids } - return ids -} +{{ end }} // Count returns the count of the given query. func ({{ $receiver }} *{{ $builder }}) Count(ctx context.Context) (int, error) { diff --git a/entc/gen/template/builder/setter.tmpl b/entc/gen/template/builder/setter.tmpl index 9d5b9ed87d..ba1a9be0c7 100644 --- a/entc/gen/template/builder/setter.tmpl +++ b/entc/gen/template/builder/setter.tmpl @@ -14,6 +14,7 @@ in the LICENSE file in the root directory of this source tree. {{- if or (hasSuffix $builder "Update") (hasSuffix $builder "UpdateOne") }} {{ $updater = true }} {{ $fields = $.MutableFields }} +{{- else if $.HasCompositeID }} {{- else if $.ID.UserDefined }} {{ $fields = append $fields $.ID }} {{- end }} @@ -62,7 +63,7 @@ in the LICENSE file in the root directory of this source tree. {{ end }} {{ end }} -{{ range $e := $.Edges }} +{{ range $e := $.EdgesWithID }} {{ $op := "add" }}{{ $idsFunc := $e.MutationAdd }}{{ if $e.Unique }}{{ $op = "set" }}{{ $idsFunc = $e.MutationSet }}{{ end }} {{/* Check if this setter was already defined by the field-setters (e.g. edge-field with the same name). */}} {{ $withSetter := not $e.HasFieldSetter }} diff --git a/entc/gen/template/builder/update.tmpl b/entc/gen/template/builder/update.tmpl index dc183f0635..1314eaf9d4 100644 --- a/entc/gen/template/builder/update.tmpl +++ b/entc/gen/template/builder/update.tmpl @@ -262,7 +262,7 @@ func ({{ $receiver }} *{{ $onebuilder }}) ExecX(ctx context.Context) { {{ $receiver := receiver $builder }} {{ $mutation := print $receiver ".mutation" }} -{{ range $e := $.Edges }} +{{ range $e := $.EdgesWithID }} {{ $func := $e.MutationClear }} // {{ $func }} clears {{ if $e.Unique }}the "{{ $e.Name }}" edge{{ else }}all "{{ $e.Name }}" edges{{ end }} to the {{ $e.Type.Name }} entity. func ({{ $receiver }} *{{ $builder }}) {{ $func }}() *{{ $builder }} { diff --git a/entc/gen/template/client.tmpl b/entc/gen/template/client.tmpl index f6416f9394..1ffc193054 100644 --- a/entc/gen/template/client.tmpl +++ b/entc/gen/template/client.tmpl @@ -163,7 +163,7 @@ func (c *{{ $client }}) Use(hooks ...Hook) { c.hooks.{{ $n.Name }} = append(c.hooks.{{ $n.Name }}, hooks...) } -// Create returns a create builder for {{ $n.Name }}. +// Create returns a builder for creating a {{ $n.Name }} entity. func (c *{{ $client }}) Create() *{{ $n.CreateName }} { mutation := new{{ $n.MutationName }}(c.config, OpCreate) return &{{ $n.CreateName }}{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -182,15 +182,22 @@ func (c *{{ $client }}) Update() *{{ $n.UpdateName }} { // UpdateOne returns an update builder for the given entity. func (c *{{ $client }}) UpdateOne({{ $rec }} *{{ $n.Name }}) *{{ $n.UpdateOneName }} { - mutation := new{{ $n.MutationName }}(c.config, OpUpdateOne, {{ print "with" $n.Name }}({{ $rec }})) + {{- if $n.HasOneFieldID }} + mutation := new{{ $n.MutationName }}(c.config, OpUpdateOne, {{ print "with" $n.Name }}({{ $rec }})) + {{- else }} + mutation := new{{ $n.MutationName }}(c.config, OpUpdateOne) + mutation.Where({{ range $id := $n.EdgeSchema.ID }}{{ $n.Package }}.{{ $id.StructField }}({{ $rec }}.{{ $id.StructField }}),{{ end }}) + {{- end }} return &{{ $n.UpdateOneName }}{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// UpdateOneID returns an update builder for the given id. -func (c *{{ $client }}) UpdateOneID(id {{ $n.ID.Type }}) *{{ $n.UpdateOneName }} { - mutation := new{{ $n.MutationName }}(c.config, OpUpdateOne, {{ print "with" $n.Name "ID" }}(id)) - return &{{ $n.UpdateOneName }}{config: c.config, hooks: c.Hooks(), mutation: mutation} -} +{{ with $n.HasOneFieldID }} + // UpdateOneID returns an update builder for the given id. + func (c *{{ $client }}) UpdateOneID(id {{ $n.ID.Type }}) *{{ $n.UpdateOneName }} { + mutation := new{{ $n.MutationName }}(c.config, OpUpdateOne, {{ print "with" $n.Name "ID" }}(id)) + return &{{ $n.UpdateOneName }}{config: c.config, hooks: c.Hooks(), mutation: mutation} + } +{{ end }} // Delete returns a delete builder for {{ $n.Name }}. func (c *{{ $client }}) Delete() *{{ $n.DeleteName }} { @@ -198,18 +205,20 @@ func (c *{{ $client }}) Delete() *{{ $n.DeleteName }} { return &{{ $n.DeleteName }}{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. -func (c *{{ $client }}) DeleteOne({{ $rec }} *{{ $n.Name }}) *{{ $n.DeleteOneName }} { - return c.DeleteOneID({{ $rec }}.ID) -} +{{ with $n.HasOneFieldID }} + // DeleteOne returns a builder for deleting the given entity. + func (c *{{ $client }}) DeleteOne({{ $rec }} *{{ $n.Name }}) *{{ $n.DeleteOneName }} { + return c.DeleteOneID({{ $rec }}.ID) + } -// DeleteOneID returns a delete builder for the given id. -func (c *{{ $client }}) DeleteOneID(id {{ $n.ID.Type }}) *{{ $n.DeleteOneName }} { - builder := c.Delete().Where({{ $n.Package }}.ID(id)) - builder.mutation.id = &id - builder.mutation.op = OpDeleteOne - return &{{ $n.DeleteOneName }}{builder} -} + // DeleteOne returns a builder for deleting the given entity by its id. + func (c *{{ $client }}) DeleteOneID(id {{ $n.ID.Type }}) *{{ $n.DeleteOneName }} { + builder := c.Delete().Where({{ $n.Package }}.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &{{ $n.DeleteOneName }}{builder} + } +{{ end }} // Query returns a query builder for {{ $n.Name }}. func (c *{{ $client }}) Query() *{{ $n.QueryName }} { @@ -223,34 +232,44 @@ func (c *{{ $client }}) Query() *{{ $n.QueryName }} { } } -// Get returns a {{ $n.Name }} entity by its id. -func (c *{{ $client }}) Get(ctx context.Context, id {{ $n.ID.Type }}) (*{{ $n.Name }}, error) { - return c.Query().Where({{ $n.Package }}.ID(id)).Only(ctx) -} +{{ with $n.HasOneFieldID }} + // Get returns a {{ $n.Name }} entity by its id. + func (c *{{ $client }}) Get(ctx context.Context, id {{ $n.ID.Type }}) (*{{ $n.Name }}, error) { + return c.Query().Where({{ $n.Package }}.ID(id)).Only(ctx) + } -// GetX is like Get, but panics if an error occurs. -func (c *{{ $client }}) GetX(ctx context.Context, id {{ $n.ID.Type }}) *{{ $n.Name }} { - obj, err := c.Get(ctx, id) - if err != nil { - panic(err) + // GetX is like Get, but panics if an error occurs. + func (c *{{ $client }}) GetX(ctx context.Context, id {{ $n.ID.Type }}) *{{ $n.Name }} { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj } - return obj -} +{{ end }} {{ range $e := $n.Edges }} {{ $builder := $e.Type.QueryName }} {{ $arg := $rec }}{{ if eq $arg "id" }}{{ $arg = "node" }}{{ end }} +{{ $func := print "Query" (pascal $e.Name) }} // Query{{ pascal $e.Name }} queries the {{ $e.Name }} edge of a {{ $n.Name }}. -func (c *{{ $client }}) Query{{ pascal $e.Name }}({{ $arg }} *{{ $n.Name }}) *{{ $builder }} { - query := &{{ $builder }}{config: c.config} - query.path = func(ctx context.Context) (fromV {{ $.Storage.Builder }}, _ error) { - {{- with extend $n "Receiver" $arg "Edge" $e "Ident" "fromV" }} - {{ $tmpl := printf "dialect/%s/query/from" $.Storage }} - {{- xtemplate $tmpl . -}} - {{- end -}} - return fromV, nil - } - return query +func (c *{{ $client }}) {{ $func }}({{ $arg }} *{{ $n.Name }}) *{{ $builder }} { + {{- if $n.HasOneFieldID }} + query := &{{ $builder }}{config: c.config} + query.path = func(ctx context.Context) (fromV {{ $.Storage.Builder }}, _ error) { + {{- with extend $n "Receiver" $arg "Edge" $e "Ident" "fromV" }} + {{ $tmpl := printf "dialect/%s/query/from" $.Storage }} + {{- xtemplate $tmpl . -}} + {{- end -}} + return fromV, nil + } + return query + {{- else }} + {{- /* For edge schema, we use the predicate-based approach. */}} + return c.Query(). + Where({{ range $id := $n.EdgeSchema.ID }}{{ $n.Package }}.{{ $id.StructField }}({{ $arg }}.{{ $id.StructField }}),{{ end }}). + {{ $func }}() + {{- end }} } {{ end }} diff --git a/entc/gen/template/dialect/sql/create.tmpl b/entc/gen/template/dialect/sql/create.tmpl index 3ecbfb197c..63433c65bc 100644 --- a/entc/gen/template/dialect/sql/create.tmpl +++ b/entc/gen/template/dialect/sql/create.tmpl @@ -19,7 +19,8 @@ func ({{ $receiver }} *{{ $builder }}) sqlSave(ctx context.Context) (*{{ $.Name } return nil, err } - {{- if and $.ID.UserDefined (or $.ID.Type.ValueScanner (not $.ID.Type.Numeric)) }} + {{- if $.HasCompositeID }} + {{- else if and $.ID.UserDefined (or $.ID.Type.ValueScanner (not $.ID.Type.Numeric)) }} if _spec.ID.Value != nil { {{- /* If the ID type is not a pointer, but implements the ValueScanner interface (e.g. UUID fields). */}} {{- if and $.ID.Type.ValueScanner (not $.ID.Type.RType.IsPtr) }} @@ -56,10 +57,12 @@ func ({{ $receiver }} *{{ $builder }}) createSpec() (*{{ $.Name }}, *sqlgraph.Cr _node = &{{ $.Name }}{config: {{ $receiver }}.config} _spec = &sqlgraph.CreateSpec{ Table: {{ $.Package }}.Table, - ID: &sqlgraph.FieldSpec{ - Type: field.{{ $.ID.Type.ConstName }}, - Column: {{ $.Package }}.{{ $.ID.Constant }}, - }, + {{- if $.HasOneFieldID }} + ID: &sqlgraph.FieldSpec{ + Type: field.{{ $.ID.Type.ConstName }}, + Column: {{ $.Package }}.{{ $.ID.Constant }}, + }, + {{- end }} } ) {{- /* Allow mutating the sqlgraph.CreateSpec by ent extensions or user templates.*/}} @@ -68,7 +71,9 @@ func ({{ $receiver }} *{{ $builder }}) createSpec() (*{{ $.Name }}, *sqlgraph.Cr {{- xtemplate $tmpl $ }} {{- end }} {{- end }} - {{- if $.ID.UserDefined }} + {{- if $.HasCompositeID }} + {{- /* TODO(a8m): Remove redudent if-s when Go 1.19 released as short-circuit was added in 1.18. */}} + {{- else if $.ID.UserDefined }} if id, ok := {{ $mutation }}.{{ $.ID.MutationGet }}(); ok { _node.ID = id _spec.ID.Value = {{ if and $.ID.Type.ValueScanner (not $.ID.Type.RType.IsPtr) }}&{{ end }}id @@ -84,7 +89,7 @@ func ({{ $receiver }} *{{ $builder }}) createSpec() (*{{ $.Name }}, *sqlgraph.Cr _node.{{ $f.StructField }} = {{ if $f.NillableValue }}&{{ end }}value } {{- end }} - {{- range $e := $.Edges }} + {{- range $e := $.EdgesWithID }} if nodes := {{ $mutation }}.{{ $e.StructField }}IDs(); len(nodes) > 0 { {{- with extend $ "Edge" $e "Nodes" true "Zero" "nil" }} {{ template "dialect/sql/defedge" . }}{{/* defined in sql/update.tmpl */}} @@ -172,16 +177,18 @@ func ({{ $receiver }} *{{ $builder }}) Save(ctx context.Context) ([]*{{ $.Name } if err != nil { return nil, err } - mutation.{{ $.ID.BuilderField }} = &nodes[i].{{ $.ID.StructField }} - mutation.done = true - {{- if and $.ID.UserDefined (or $.ID.IsString $.ID.IsUUID $.ID.IsBytes $.ID.IsOther) }} - {{- /* Do nothing, because these 2 types must be supplied by the user. */ -}} - {{- else }} - if specs[i].ID.Value != nil {{ if $.ID.UserDefined }}&& nodes[i].ID == 0{{ end }} { - id := specs[i].ID.Value.(int64) - nodes[i].ID = {{ $.ID.Type }}(id) - } + {{- if $.HasOneFieldID }} + mutation.{{ $.ID.BuilderField }} = &nodes[i].{{ $.ID.StructField }} + {{- if and $.ID.UserDefined (or $.ID.IsString $.ID.IsUUID $.ID.IsBytes $.ID.IsOther) }} + {{- /* Do nothing, because these 2 types must be supplied by the user. */ -}} + {{- else }} + if specs[i].ID.Value != nil {{ if $.ID.UserDefined }}&& nodes[i].ID == 0{{ end }} { + id := specs[i].ID.Value.(int64) + nodes[i].ID = {{ $.ID.Type }}(id) + } + {{- end }} {{- end }} + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/entc/gen/template/dialect/sql/decode.tmpl b/entc/gen/template/dialect/sql/decode.tmpl index 25fe5baab8..9a8902bdbe 100644 --- a/entc/gen/template/dialect/sql/decode.tmpl +++ b/entc/gen/template/dialect/sql/decode.tmpl @@ -9,8 +9,11 @@ in the LICENSE file in the root directory of this source tree. {{ define "dialect/sql/decode/one" }} {{ $receiver := $.Receiver }} -{{ $idscantype := $.ID.NewScanType }}{{ if not $.ID.UserDefined }}{{ $idscantype = "new(sql.NullInt64)" }}{{ end }} -{{ $ctypes := dict $idscantype (list $.ID.Constant) }} +{{ $ctypes := dict }} +{{ if $.HasOneFieldID }} + {{ $idscantype := $.ID.NewScanType }}{{ if not $.ID.UserDefined }}{{ $idscantype = "new(sql.NullInt64)" }}{{ end }} + {{ $ctypes = set $ctypes $idscantype (list $.ID.Constant) }} +{{ end }} {{ range $f := $.Fields }} {{ $names := list }} {{ if hasKey $ctypes $f.NewScanType }} @@ -50,18 +53,20 @@ func ({{ $receiver }} *{{ $.Name }}) assignValues(columns []string, values []int {{- $idx := "i" }}{{ if eq $idx $receiver }}{{ $idx = "j" }}{{ end }} for {{ $idx }} := range columns { switch columns[{{ $idx }}] { - case {{ $.Package }}.{{ $.ID.Constant }}: - {{- if and $.ID.UserDefined (or $.ID.IsString $.ID.IsUUID $.ID.IsBytes $.ID.IsOther) }} - {{- with extend $ "Idx" $idx "Field" $.ID "Rec" $receiver }} - {{ template "dialect/sql/decode/field" . }} + {{- if $.HasOneFieldID }} + case {{ $.Package }}.{{ $.ID.Constant }}: + {{- if and $.ID.UserDefined (or $.ID.IsString $.ID.IsUUID $.ID.IsBytes $.ID.IsOther) }} + {{- with extend $ "Idx" $idx "Field" $.ID "Rec" $receiver }} + {{ template "dialect/sql/decode/field" . }} + {{- end }} + {{- else }} + value, ok := values[{{ $idx }}].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + {{ $receiver }}.ID = {{ $.ID.Type }}(value.Int64) {{- end }} - {{- else }} - value, ok := values[{{ $idx }}].(*sql.NullInt64) - if !ok { - return fmt.Errorf("unexpected type %T for field id", value) - } - {{ $receiver }}.ID = {{ $.ID.Type }}(value.Int64) - {{- end }} + {{- end }} {{- range $f := $.Fields }} case {{ $.Package }}.{{ $f.Constant }}: {{- with extend $ "Idx" $idx "Field" $f "Rec" $receiver }} diff --git a/entc/gen/template/dialect/sql/delete.tmpl b/entc/gen/template/dialect/sql/delete.tmpl index 3c51491811..72b84610e5 100644 --- a/entc/gen/template/dialect/sql/delete.tmpl +++ b/entc/gen/template/dialect/sql/delete.tmpl @@ -15,10 +15,12 @@ func ({{ $receiver}} *{{ $builder }}) sqlExec(ctx context.Context) (int, error) _spec := &sqlgraph.DeleteSpec{ Node: &sqlgraph.NodeSpec{ Table: {{ $.Package }}.Table, - ID: &sqlgraph.FieldSpec{ - Type: field.{{ $.ID.Type.ConstName }}, - Column: {{ $.Package }}.{{ $.ID.Constant }}, - }, + {{- if $.HasOneFieldID }} + ID: &sqlgraph.FieldSpec{ + Type: field.{{ $.ID.Type.ConstName }}, + Column: {{ $.Package }}.{{ $.ID.Constant }}, + }, + {{- end }} }, } {{- /* Allow mutating the sqlgraph.DeleteSpec by ent extensions or user templates.*/}} diff --git a/entc/gen/template/dialect/sql/meta.tmpl b/entc/gen/template/dialect/sql/meta.tmpl index 7f2ae3df06..17c0681a7a 100644 --- a/entc/gen/template/dialect/sql/meta.tmpl +++ b/entc/gen/template/dialect/sql/meta.tmpl @@ -9,7 +9,11 @@ in the LICENSE file in the root directory of this source tree. {{/* constants needed for sql dialects. */}} {{ define "dialect/sql/meta/constants" }} {{- range $t := $.RelatedTypes }} - {{- if ne $t.ID.StorageKey $.ID.StorageKey }} + {{- $withEID := $.HasCompositeID }} + {{- if and (not $withEID) $t.HasOneFieldID }} + {{- if ne $t.ID.StorageKey $.ID.StorageKey }}{{ $withEID = true }}{{ end }} + {{- end }} + {{- if $withEID }} // {{ $t.Name }}FieldID holds the string denoting the ID field of the {{ $t.Name }}. {{ $t.Name }}FieldID = "{{ $t.ID.StorageKey }}" {{- end }} @@ -36,7 +40,9 @@ in the LICENSE file in the root directory of this source tree. {{ define "dialect/sql/meta/variables" }} // Columns holds all SQL columns for {{ lower $.Name }} fields. var Columns = []string{ - {{ $.ID.Constant }}, + {{- if $.HasOneFieldID }} + {{ $.ID.Constant }}, + {{- end }} {{- range $f := $.Fields }} {{ $f.Constant }}, {{- end }} diff --git a/entc/gen/template/dialect/sql/predicate.tmpl b/entc/gen/template/dialect/sql/predicate.tmpl index 40d63cbaaa..a4af3d9e9c 100644 --- a/entc/gen/template/dialect/sql/predicate.tmpl +++ b/entc/gen/template/dialect/sql/predicate.tmpl @@ -61,11 +61,22 @@ in the LICENSE file in the root directory of this source tree. {{ define "dialect/sql/predicate/edge/has" -}} {{- $e := $.Scope.Edge -}} - {{- $refid := $.ID.Constant }}{{ if ne $e.Type.ID.StorageKey $.ID.StorageKey }}{{ $refid = print $e.Type.Name "FieldID" }}{{ end -}} func(s *sql.Selector) { step := sqlgraph.NewStep( - sqlgraph.From(Table, {{ $.ID.Constant }}), - sqlgraph.To({{ $e.TableConstant }}, {{ $refid }}), + {{- if $.HasCompositeID }} + {{- /* Query that goes from the edge schema. */}} + sqlgraph.From(Table, {{ $e.ColumnConstant }}), + sqlgraph.To({{ $e.InverseTableConstant }}, {{ print $e.Type.Name "FieldID" }}), + {{- else }} + sqlgraph.From(Table, {{ $.ID.Constant }}), + {{- if $e.Type.HasOneFieldID }} + {{- $refid := $.ID.Constant }}{{ if ne $e.Type.ID.StorageKey $.ID.StorageKey }}{{ $refid = print $e.Type.Name "FieldID" }}{{ end }} + sqlgraph.To({{ $e.TableConstant }}, {{ $refid }}), + {{- else }} + {{- /* Query that goes to the edge schema. */}} + sqlgraph.To({{ $e.TableConstant }}, {{ $e.ColumnConstant }}), + {{- end }} + {{- end }} sqlgraph.Edge(sqlgraph.{{ $e.Rel.Type }}, {{ $e.IsInverse }}, {{ $e.TableConstant }}, {{- if $e.M2M -}} {{ $e.PKConstant }}... @@ -86,11 +97,22 @@ in the LICENSE file in the root directory of this source tree. {{ define "dialect/sql/predicate/edge/haswith" -}} {{- $e := $.Scope.Edge -}} - {{- $refid := $.ID.Constant }}{{ if ne $e.Type.ID.StorageKey $.ID.StorageKey }}{{ $refid = print $e.Type.Name "FieldID" }}{{ end -}} func(s *sql.Selector) { step := sqlgraph.NewStep( - sqlgraph.From(Table, {{ $.ID.Constant }}), - sqlgraph.To({{ if ne $.Table $e.Type.Table }}{{ $e.InverseTableConstant }}{{ else }}Table{{ end }}, {{ $refid }}), + {{- if $.HasCompositeID }} + {{- /* Query that goes from the edge schema. */}} + sqlgraph.From(Table, {{ $e.ColumnConstant }}), + sqlgraph.To({{ $e.InverseTableConstant }}, {{ print $e.Type.Name "FieldID" }}), + {{- else }} + sqlgraph.From(Table, {{ $.ID.Constant }}), + {{- if $e.Type.HasOneFieldID }} + {{- $refid := $.ID.Constant }}{{ if ne $e.Type.ID.StorageKey $.ID.StorageKey }}{{ $refid = print $e.Type.Name "FieldID" }}{{ end }} + sqlgraph.To({{ if ne $.Table $e.Type.Table }}{{ $e.InverseTableConstant }}{{ else }}Table{{ end }}, {{ $refid }}), + {{- else }} + {{- /* Query that goes to the edge schema. */}} + sqlgraph.To({{ if ne $.Table $e.Type.Table }}{{ $e.InverseTableConstant }}{{ else }}Table{{ end }}, {{ $e.ColumnConstant }}), + {{- end }} + {{- end }} sqlgraph.Edge(sqlgraph.{{ $e.Rel.Type }}, {{ $e.IsInverse }}, {{ $e.TableConstant }}, {{- if $e.M2M -}} {{ $e.PKConstant }}... diff --git a/entc/gen/template/dialect/sql/query.tmpl b/entc/gen/template/dialect/sql/query.tmpl index 4ba95f14f6..1f52ecf939 100644 --- a/entc/gen/template/dialect/sql/query.tmpl +++ b/entc/gen/template/dialect/sql/query.tmpl @@ -96,11 +96,17 @@ func ({{ $receiver }} *{{ $builder }}) sqlCount(ctx context.Context) (int, error {{- xtemplate $tmpl $ }} {{- end }} {{- end }} - _spec.Node.Columns = {{ $receiver }}.fields - if len({{ $receiver }}.fields) > 0 { - {{- /* In case of field selection, configure query to unique only if was explicitly set to true. */}} - _spec.Unique = {{ $receiver }}.unique != nil && *{{ $receiver }}.unique - } + {{- if $.HasCompositeID }} + {{- /* In case of an edge schema with composite primary-key, there is no need to SELECT DISTINCT. */}} + _spec.Unique = false + _spec.Node.Columns = nil + {{- else }} + _spec.Node.Columns = {{ $receiver }}.fields + if len({{ $receiver }}.fields) > 0 { + {{- /* In case of field selection, configure query to unique only if was explicitly set to true. */}} + _spec.Unique = {{ $receiver }}.unique != nil && *{{ $receiver }}.unique + } + {{- end }} return sqlgraph.CountNodes(ctx, {{ $receiver }}.driver, _spec) } @@ -117,10 +123,12 @@ func ({{ $receiver }} *{{ $builder }}) querySpec() *sqlgraph.QuerySpec { Node: &sqlgraph.NodeSpec{ Table: {{ $.Package }}.Table, Columns: {{ $.Package }}.Columns, - ID: &sqlgraph.FieldSpec{ - Type: field.{{ $.ID.Type.ConstName }}, - Column: {{ $.Package }}.{{ $.ID.Constant }}, - }, + {{- if $.HasOneFieldID }} + ID: &sqlgraph.FieldSpec{ + Type: field.{{ $.ID.Type.ConstName }}, + Column: {{ $.Package }}.{{ $.ID.Constant }}, + }, + {{- end }} }, From: {{ $receiver }}.sql, Unique: true, @@ -130,12 +138,18 @@ func ({{ $receiver }} *{{ $builder }}) querySpec() *sqlgraph.QuerySpec { } if fields := {{ $receiver }}.fields; len(fields) > 0 { _spec.Node.Columns = make([]string, 0, len(fields)) - _spec.Node.Columns = append(_spec.Node.Columns, {{ $.Package }}.{{ $.ID.Constant }}) - for i := range fields { - if fields[i] != {{ $.Package }}.{{ $.ID.Constant }} { + {{- if $.HasOneFieldID }} + _spec.Node.Columns = append(_spec.Node.Columns, {{ $.Package }}.{{ $.ID.Constant }}) + for i := range fields { + if fields[i] != {{ $.Package }}.{{ $.ID.Constant }} { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + {{- else }} + for i := range fields { _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) } - } + {{- end }} } if ps := {{ $receiver }}.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { @@ -218,7 +232,7 @@ func ({{ $receiver }} *{{ $builder }}) sqlQuery(ctx context.Context) *sql.Select {{/* query/path defines the query generation for path of a given edge. */}} {{ define "dialect/sql/query/path" }} {{- $n := $ }} {{/* the node we start the query from. */}} - {{- $e := $.Scope.Edge }} {{/* the edge we need to genegrate the path to. */}} + {{- $e := $.Scope.Edge }} {{/* the edge we need to generate the path to. */}} {{- $ident := $.Scope.Ident -}} {{- $receiver := $.Scope.Receiver }} selector := {{ $receiver }}.sqlQuery(ctx) @@ -226,8 +240,8 @@ func ({{ $receiver }} *{{ $builder }}) sqlQuery(ctx context.Context) *sql.Select return nil, err } step := sqlgraph.NewStep( - sqlgraph.From({{ $n.Package }}.Table, {{ $n.Package }}.{{ $n.ID.Constant }}, selector), - sqlgraph.To({{ $e.Type.Package }}.Table, {{ $e.Type.Package }}.{{ $e.Type.ID.Constant }}), + sqlgraph.From({{ $n.Package }}.Table, {{ $n.Package }}.{{ if $n.HasCompositeID }}{{ $e.ColumnConstant }}{{ else }}{{ $n.ID.Constant }}{{ end }}, selector), + sqlgraph.To({{ $e.Type.Package }}.Table, {{ $e.Type.Package }}.{{ if $e.Type.HasCompositeID }}{{ $e.Ref.ColumnConstant }}{{ else }}{{ $e.Type.ID.Constant }}{{ end }}), sqlgraph.Edge(sqlgraph.{{ $e.Rel.Type }}, {{ $e.IsInverse }}, {{ $n.Package }}.{{ $e.TableConstant }}, {{- if $e.M2M -}} {{ $n.Package }}.{{ $e.PKConstant }}... @@ -254,7 +268,7 @@ func ({{ $receiver }} *{{ $builder }}) sqlQuery(ctx context.Context) *sql.Select id := {{ $receiver }}.ID step := sqlgraph.NewStep( sqlgraph.From({{ $n.Package }}.Table, {{ $n.Package }}.{{ $n.ID.Constant }}, id), - sqlgraph.To({{ $e.Type.Package }}.Table, {{ $e.Type.Package }}.{{ $e.Type.ID.Constant }}), + sqlgraph.To({{ $e.Type.Package }}.Table, {{ $e.Type.Package }}.{{ if $e.Type.HasCompositeID }}{{ $e.Ref.ColumnConstant }}{{ else }}{{ $e.Type.ID.Constant }}{{ end }}), sqlgraph.Edge(sqlgraph.{{ $e.Rel.Type }}, {{ $e.IsInverse }}, {{ $n.Package }}.{{ $e.TableConstant }}, {{- if $e.M2M -}} {{ $n.Package }}.{{ $e.PKConstant }}... @@ -391,7 +405,7 @@ func ({{ $receiver }} *{{ $builder }}) sqlQuery(ctx context.Context) *sql.Select {{- end }} node, ok := nodeids[{{ if $fk.Field.Nillable }}*{{ end }}fk] if !ok { - return nil, fmt.Errorf(`unexpected foreign-key "{{ $fk.Field.Name }}" returned %v for node %v`, {{ if $fk.Field.Nillable }}*{{ end }}fk, n.ID) + return nil, fmt.Errorf(`unexpected foreign-key "{{ $fk.Field.Name }}" returned %v for node %v`, {{ if $fk.Field.Nillable }}*{{ end }}fk, n{{ if $e.Type.HasOneFieldID }}.ID{{ end }}) } node.Edges.{{ $e.StructField }} = {{ if $e.Unique }}n{{ else }}append(node.Edges.{{ $e.StructField }}, n){{ end }} } diff --git a/entc/gen/template/dialect/sql/update.tmpl b/entc/gen/template/dialect/sql/update.tmpl index 1694222d0b..05f6461494 100644 --- a/entc/gen/template/dialect/sql/update.tmpl +++ b/entc/gen/template/dialect/sql/update.tmpl @@ -20,30 +20,44 @@ func ({{ $receiver }} *{{ $builder }}) sqlSave(ctx context.Context) ({{ $ret }} Node: &sqlgraph.NodeSpec{ Table: {{ $.Package }}.Table, Columns: {{ $.Package }}.Columns, - ID: &sqlgraph.FieldSpec{ - Type: field.{{ $.ID.Type.ConstName }}, - Column: {{ $.Package }}.{{ $.ID.Constant }}, - }, + {{- if $.HasOneFieldID }} + ID: &sqlgraph.FieldSpec{ + Type: field.{{ $.ID.Type.ConstName }}, + Column: {{ $.Package }}.{{ $.ID.Constant }}, + }, + {{- end }} }, } {{- if $one }} - id, ok := {{ $mutation }}.{{ $.ID.MutationGet }}() - if !ok { - return {{ $zero }}, &ValidationError{Name: "{{ $.ID.Name }}", err: errors.New(`{{ $pkg }}: missing "{{ $.Name }}.{{ $.ID.Name }}" for update`)} - } - _spec.Node.ID.Value = id - if fields := {{ $receiver }}.fields; len(fields) > 0 { - _spec.Node.Columns = make([]string, 0, len(fields)) - _spec.Node.Columns = append(_spec.Node.Columns, {{ $.Package }}.{{ $.ID.Constant }}) - for _, f := range fields { - if !{{ $.Package }}.ValidColumn(f) { - return nil, &ValidationError{Name: f, err: fmt.Errorf("{{ $pkg }}: invalid field %q for query", f)} + {{- if $.HasOneFieldID }} + id, ok := {{ $mutation }}.{{ $.ID.MutationGet }}() + if !ok { + return {{ $zero }}, &ValidationError{Name: "{{ $.ID.Name }}", err: errors.New(`{{ $pkg }}: missing "{{ $.Name }}.{{ $.ID.Name }}" for update`)} + } + _spec.Node.ID.Value = id + if fields := {{ $receiver }}.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, {{ $.Package }}.{{ $.ID.Constant }}) + for _, f := range fields { + if !{{ $.Package }}.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("{{ $pkg }}: invalid field %q for query", f)} + } + if f != {{ $.Package }}.{{ $.ID.Constant }} { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } } - if f != {{ $.Package }}.{{ $.ID.Constant }} { - _spec.Node.Columns = append(_spec.Node.Columns, f) + } + {{- else }} + if fields := {{ $receiver }}.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, len(fields)) + for i, f := range fields { + if !{{ $.Package }}.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("{{ $pkg }}: invalid field %q for query", f)} + } + _spec.Node.Columns[i] = f } } - } + {{- end }} {{- end }} if ps := {{ $mutation }}.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { @@ -80,7 +94,7 @@ func ({{ $receiver }} *{{ $builder }}) sqlSave(ctx context.Context) ({{ $ret }} } {{- end }} {{- end }} - {{- range $e := $.Edges }} + {{- range $e := $.EdgesWithID }} if {{ $mutation }}.{{ $e.MutationCleared }}() { {{- with extend $ "Edge" $e }} {{ template "dialect/sql/defedge" . }} @@ -131,6 +145,7 @@ func ({{ $receiver }} *{{ $builder }}) sqlSave(ctx context.Context) ({{ $ret }} {{ define "dialect/sql/defedge" }} {{- $e := $.Scope.Edge -}} + {{- $receiver := pascal $.Scope.Builder | receiver -}} edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.{{ $e.Rel.Type }}, Inverse: {{ $e.IsInverse }}, @@ -155,4 +170,13 @@ func ({{ $receiver }} *{{ $builder }}) sqlSave(ctx context.Context) ({{ $ret }} edge.Target.Nodes = append(edge.Target.Nodes, k) } {{- end }} + {{- with $e.Through }} + {{- if .HasDefault }} + createE := &{{ .CreateName }}{config: {{ $receiver }}.config, mutation: new{{ .MutationName }}({{ $receiver }}.config, OpCreate)} + {{- /* Skip error handling here as this check was already handled. */}} + {{ if or $.NumHooks $.NumPolicy }}_ = {{ end }}createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + {{- end }} + {{- end }} {{- end }} diff --git a/entc/gen/template/ent.tmpl b/entc/gen/template/ent.tmpl index 239146d0d9..e4ac10a1b9 100644 --- a/entc/gen/template/ent.tmpl +++ b/entc/gen/template/ent.tmpl @@ -27,13 +27,15 @@ import ( {{- end }} type {{ $.Name }} struct { config {{ template "model/omittags" $ }} - // ID of the ent. - {{- if $.ID.Comment }} - {{- range $line := split $.ID.Comment "\n" }} - // {{ $line }} + {{- if $.HasOneFieldID }} + // ID of the ent. + {{- if $.ID.Comment }} + {{- range $line := split $.ID.Comment "\n" }} + // {{ $line }} + {{- end }} {{- end }} + ID {{ $.ID.Type }} {{ with $.Annotations.Fields.StructTag.id }}`{{ . }}`{{ else }}`{{ $.ID.StructTag }}`{{ end }} {{- end }} - ID {{ $.ID.Type }} {{ with $.Annotations.Fields.StructTag.id }}`{{ . }}`{{ else }}`{{ $.ID.StructTag }}`{{ end }} {{- range $f := $.Fields }} {{- $tag := $f.StructTag }}{{ with $tags := $.Annotations.Fields.StructTag }}{{ with index $tags $f.Name }}{{ $tag = . }}{{ end }}{{ end }} {{- template "model/fieldcomment" $f }} @@ -145,15 +147,20 @@ func ({{ $receiver }} {{ $slice }}) config(cfg config) { func ({{ $receiver }} *{{ $.Name }}) String() string { var builder strings.Builder builder.WriteString("{{ $.Name }}(") - builder.WriteString(fmt.Sprintf("id=%v", {{ $receiver }}.ID)) + {{- if $.HasOneFieldID }} + builder.WriteString(fmt.Sprintf("id=%v{{ if $.Fields }}, {{ end }}", {{ $receiver }}.ID)) + {{- end }} {{- range $i, $f := $.Fields }} + {{- if ne $i 0 }} + builder.WriteString(", ") + {{- end }} {{- if $f.Sensitive }} - builder.WriteString(", {{ $f.Name }}={{ print "" }}") + builder.WriteString("{{ $f.Name }}={{ print "" }}") {{- else }} {{- $sf := printf "%s.%s" $receiver $f.StructField }} {{- if $f.Nillable }} if v := {{ $sf }}; v != nil { - builder.WriteString(", {{ $f.Name }}=") + builder.WriteString("{{ $f.Name }}=") {{- if and $f.IsTime (not $f.HasGoType) }} builder.WriteString(v.Format(time.ANSIC)) {{- else if and $f.IsString (not $f.HasGoType) }} @@ -163,7 +170,7 @@ func ({{ $receiver }} {{ $slice }}) config(cfg config) { {{- end }} } {{- else }} - builder.WriteString(", {{ $f.Name }}=") + builder.WriteString("{{ $f.Name }}=") {{- if and $f.IsTime (not $f.HasGoType) }} builder.WriteString({{ $sf }}.Format(time.ANSIC)) {{- else if and $f.IsString (not $f.HasGoType) }} diff --git a/entc/gen/template/import.tmpl b/entc/gen/template/import.tmpl index ef3e067b8d..5ee8da3d8d 100644 --- a/entc/gen/template/import.tmpl +++ b/entc/gen/template/import.tmpl @@ -17,8 +17,10 @@ import ( {{- /* Ignore generting on graph specififc templates */}} {{- if not (eq $.Config.Package $.Package) }} "{{ $.Config.Package }}/predicate" - {{- with $.ID.Type.PkgPath }} - "{{ . }}" + {{- if $.HasOneFieldID }} + {{- with $.ID.Type.PkgPath }} + "{{ . }}" + {{- end }} {{- end }} {{- /* Import external packages */}} {{- template "import/types" $ }} @@ -36,7 +38,7 @@ import ( {{/* A template for importing fields with custom types */}} {{ define "import/types" -}} - {{- $fields := $.Fields }}{{ if $.ID.UserDefined }}{{ $fields = append $fields $.ID }}{{ end }} + {{- $fields := $.Fields }}{{ if $.HasOneFieldID }}{{ if $.ID.UserDefined }}{{ $fields = append $fields $.ID }}{{ end }}{{ end }} {{- range $f := $fields }} {{- $pkg := $f.Type.PkgPath }} {{- if and $pkg (not (hasImport (base $pkg ))) }} diff --git a/entc/gen/template/meta.tmpl b/entc/gen/template/meta.tmpl index b8e026e45e..b783db578f 100644 --- a/entc/gen/template/meta.tmpl +++ b/entc/gen/template/meta.tmpl @@ -17,8 +17,10 @@ in the LICENSE file in the root directory of this source tree. const ( // Label holds the string label denoting the {{ lower $.Name }} type in the database. Label = "{{ $.Label }}" - // {{ $.ID.Constant }} holds the string denoting the id field in the database. - {{ $.ID.Constant }} = "{{ $.ID.StorageKey }}" + {{- if $.HasOneFieldID }} + // {{ $.ID.Constant }} holds the string denoting the id field in the database. + {{ $.ID.Constant }} = "{{ $.ID.StorageKey }}" + {{- end }} {{- range $f := $.Fields }} {{- $field := $f.Constant }} // {{ $field }} holds the string denoting the {{ lower $f.Name }} field in the database. @@ -44,7 +46,7 @@ const ( {{ end }} {{/* Has at least one field (not enum) with default value */}} -{{ $fields := $.Fields }}{{ if $.ID.UserDefined }}{{ $fields = append $fields $.ID }}{{ end }} +{{ $fields := $.Fields }}{{ if $.HasOneFieldID }}{{ if $.ID.UserDefined }}{{ $fields = append $fields $.ID }}{{ end }}{{ end }} {{ $hasDefault := false }}{{ range $f := $fields }}{{ if and $f.Default (not $f.IsEnum) }}{{ $hasDefault = true }}{{ end }}{{ end }} {{/* Generate global variables for hooks, validators and policy checkers */}} @@ -68,7 +70,7 @@ const ( {{- if $.NumPolicy }} Policy ent.Policy {{- end }} - {{- $fields := $.Fields }}{{ if $.ID.UserDefined }}{{ $fields = append $fields $.ID }}{{ end }} + {{- $fields := $.Fields }}{{ if $.HasOneFieldID }}{{ if $.ID.UserDefined }}{{ $fields = append $fields $.ID }}{{ end }}{{ end }} {{- range $f := $fields }} {{- if and $f.Default (not $f.IsEnum) }} {{- $default := $f.DefaultName }} diff --git a/entc/gen/template/runtime.tmpl b/entc/gen/template/runtime.tmpl index 2fc52d2a2a..7bed59a7de 100644 --- a/entc/gen/template/runtime.tmpl +++ b/entc/gen/template/runtime.tmpl @@ -134,7 +134,7 @@ func init() { _ = {{ $pkg }}MixinFields{{ $i }} {{- end }} {{- end }} - {{- $fields := $n.Fields }}{{ if $n.ID.UserDefined }}{{ $fields = append $fields $n.ID }}{{ end }} + {{- $fields := $n.Fields }}{{ if $n.HasOneFieldID }}{{ if $n.ID.UserDefined }}{{ $fields = append $fields $n.ID }}{{ end }}{{ end }} {{- with $fields }} {{ $pkg }}Fields := {{ $schema }}.{{ $n.Name }}{}.Fields() _ = {{ $pkg }}Fields diff --git a/entc/gen/template/where.tmpl b/entc/gen/template/where.tmpl index 1199da1ab8..4e4d13ac06 100644 --- a/entc/gen/template/where.tmpl +++ b/entc/gen/template/where.tmpl @@ -14,26 +14,28 @@ in the LICENSE file in the root directory of this source tree. {{ template "import" $ }} -// ID filters vertices based on their ID field. -func ID(id {{ $.ID.Type }}) predicate.{{ $.Name }} { - return predicate.{{ $.Name }}( - {{- $tmpl := printf "dialect/%s/predicate/id" $.Storage }} - {{- xtemplate $tmpl $ -}} - ) -} - -{{ range $op := $.ID.Ops }} - {{ $arg := "id" }}{{ if $op.Variadic }}{{ $arg = "ids" }}{{ end }} - {{ $func := printf "ID%s" $op.Name }} - // {{ $func }} applies the {{ $op.Name }} predicate on the ID field. - func {{ $func }}({{ $arg }} {{ if $op.Variadic }}...{{ end }}{{ $.ID.Type }}) predicate.{{ $.Name }} { +{{ if .HasOneFieldID }} + // ID filters vertices based on their ID field. + func ID(id {{ $.ID.Type }}) predicate.{{ $.Name }} { return predicate.{{ $.Name }}( - {{- with extend $ "Arg" $arg "Op" $op "Storage" $.Storage -}} - {{ $tmpl := printf "dialect/%s/predicate/id/ops" $.Storage }} - {{- xtemplate $tmpl . }} - {{- end -}} + {{- $tmpl := printf "dialect/%s/predicate/id" $.Storage }} + {{- xtemplate $tmpl $ -}} ) } + + {{ range $op := $.ID.Ops }} + {{ $arg := "id" }}{{ if $op.Variadic }}{{ $arg = "ids" }}{{ end }} + {{ $func := printf "ID%s" $op.Name }} + // {{ $func }} applies the {{ $op.Name }} predicate on the ID field. + func {{ $func }}({{ $arg }} {{ if $op.Variadic }}...{{ end }}{{ $.ID.Type }}) predicate.{{ $.Name }} { + return predicate.{{ $.Name }}( + {{- with extend $ "Arg" $arg "Op" $op "Storage" $.Storage -}} + {{ $tmpl := printf "dialect/%s/predicate/id/ops" $.Storage }} + {{- xtemplate $tmpl . }} + {{- end -}} + ) + } + {{ end }} {{ end }} {{ range $f := $.Fields }} @@ -118,7 +120,7 @@ func ID(id {{ $.ID.Type }}) predicate.{{ $.Name }} { // And groups predicates with the AND operator between them. func And(predicates ...predicate.{{ $.Name }}) predicate.{{ $.Name }} { return predicate.{{ $.Name }}( - {{- $tmpl = printf "dialect/%s/predicate/and" $.Storage }} + {{- $tmpl := printf "dialect/%s/predicate/and" $.Storage }} {{- xtemplate $tmpl . -}} ) } diff --git a/entc/gen/type.go b/entc/gen/type.go index 2ac5461abd..64b5b840e0 100644 --- a/entc/gen/type.go +++ b/entc/gen/type.go @@ -52,6 +52,12 @@ type ( // Annotations that were defined for the field in the schema. // The mapping is from the Annotation.Name() to a JSON decoded object. Annotations Annotations + // EdgeSchema indicates that this type (schema) is being used as an "edge schema". + // The To and From fields holds references to the edges that go "through" this type. + EdgeSchema struct { + ID []*Field + To, From *Edge + } } // Field holds the information of a type field used for the templates. @@ -79,7 +85,7 @@ type ( Immutable bool // StructTag of the field. default to "json". StructTag string - // Validators holds the number of validators this field have. + // Validators holds the number of validators the field have. Validators int // Position info of the field. Position *load.Position @@ -113,6 +119,8 @@ type ( // Owner holds the type of the edge-owner. For assoc-edges it's the // type that holds the edge, for inverse-edges, it's the assoc type. Owner *Type + // Through edge schema type. + Through *Type // StructTag of the edge-field in the struct. default to "json". StructTag string // Relation holds the relation info of an edge. @@ -251,6 +259,22 @@ func NewType(c *Config, schema *load.Schema) (*Type, error) { return typ, nil } +// IsEdgeSchema indicates if the type (schema) is used as an edge-schema. +// i.e. is being used by an edge (or its inverse) with edge.Through modifier. +func (t Type) IsEdgeSchema() bool { + return t.EdgeSchema.To != nil || t.EdgeSchema.From != nil +} + +// HasCompositeID indicates if the type has a composite ID field. +func (t Type) HasCompositeID() bool { + return t.IsEdgeSchema() && len(t.EdgeSchema.ID) > 1 +} + +// HasOneFieldID indicates if the type has an ID with one field (not composite). +func (t Type) HasOneFieldID() bool { + return !t.HasCompositeID() +} + // Label returns Gremlin label name of the node/type. func (t Type) Label() string { return snake(t.Name) @@ -294,6 +318,17 @@ func (t Type) Receiver() string { return receiver(t.Name) } +// hasEdge returns true if this type as an edge (reverse or assoc) +/// with the given name. +func (t Type) hasEdge(name string) bool { + for _, e := range t.Edges { + if name == e.Name { + return true + } + } + return false +} + // HasAssoc returns true if this type has an assoc-edge (edge.To) // with the given name. faster than map access for most cases. func (t Type) HasAssoc(name string) (*Edge, bool) { @@ -308,7 +343,7 @@ func (t Type) HasAssoc(name string) (*Edge, bool) { // HasValidators reports if any of the type's field has validators. func (t Type) HasValidators() bool { fields := t.Fields - if t.ID.UserDefined { + if t.HasOneFieldID() && t.ID.UserDefined { fields = append(fields, t.ID) } for _, f := range fields { @@ -322,7 +357,7 @@ func (t Type) HasValidators() bool { // HasDefault reports if any of this type's fields has default value on creation. func (t Type) HasDefault() bool { fields := t.Fields - if t.ID.UserDefined { + if t.HasOneFieldID() && t.ID.UserDefined { fields = append(fields, t.ID) } for _, f := range fields { @@ -388,6 +423,17 @@ func (t Type) FKEdges() (edges []*Edge) { return } +// EdgesWithID returns all edges that point to entities with non-composite identifiers. +// These types of edges can be created, updated and deleted by their identifiers. +func (t Type) EdgesWithID() (edges []*Edge) { + for _, e := range t.Edges { + if !e.Type.HasCompositeID() { + edges = append(edges, e) + } + } + return +} + // RuntimeMixin returns schema mixin that needs to be loaded at // runtime. For example, for default values, validators or hooks. func (t Type) RuntimeMixin() bool { @@ -398,7 +444,7 @@ func (t Type) RuntimeMixin() bool { func (t Type) MixedInFields() []int { idx := make(map[int]struct{}) fields := t.Fields - if t.ID.UserDefined { + if t.HasOneFieldID() && t.ID.UserDefined { fields = append(fields, t.ID) } for _, f := range fields { @@ -892,7 +938,7 @@ func aliases(g *Graph) { if name == "" && f.Type.PkgPath != "" { name = path.Base(f.Type.PkgPath) } - // An user-defined type already uses the + // A user-defined type already uses the // package local name. if n, ok := names[name]; ok { // By default, a package named "pet" will be named as "entpet". @@ -1764,7 +1810,7 @@ func structTag(name, tag string) string { // builderField returns the struct field for the given name // and ensures it doesn't conflict with Go keywords and other -// builder fields and it's not exported. +// builder fields, and it is not exported. func builderField(name string) string { _, ok := privateField[name] if ok || token.Lookup(name).IsKeyword() || strings.ToUpper(name[:1]) == name[:1] { @@ -1773,6 +1819,18 @@ func builderField(name string) string { return name } +// fieldAnnotate extracts the field annotation from a loaded annotation format. +func fieldAnnotate(annotation map[string]interface{}) *field.Annotation { + annotate := &field.Annotation{} + if annotation == nil || annotation[annotate.Name()] == nil { + return nil + } + if buf, err := json.Marshal(annotation[annotate.Name()]); err == nil { + _ = json.Unmarshal(buf, &annotate) + } + return annotate +} + // entsqlAnnotate extracts the entsql annotation from a loaded annotation format. func entsqlAnnotate(annotation map[string]interface{}) *entsql.Annotation { annotate := &entsql.Annotation{} diff --git a/entc/integration/cascadelete/ent/client.go b/entc/integration/cascadelete/ent/client.go index e51662e6d9..fd41da8490 100644 --- a/entc/integration/cascadelete/ent/client.go +++ b/entc/integration/cascadelete/ent/client.go @@ -157,7 +157,7 @@ func (c *CommentClient) Use(hooks ...Hook) { c.hooks.Comment = append(c.hooks.Comment, hooks...) } -// Create returns a create builder for Comment. +// Create returns a builder for creating a Comment entity. func (c *CommentClient) Create() *CommentCreate { mutation := newCommentMutation(c.config, OpCreate) return &CommentCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -192,12 +192,12 @@ func (c *CommentClient) Delete() *CommentDelete { return &CommentDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *CommentClient) DeleteOne(co *Comment) *CommentDeleteOne { return c.DeleteOneID(co.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *CommentClient) DeleteOneID(id int) *CommentDeleteOne { builder := c.Delete().Where(comment.ID(id)) builder.mutation.id = &id @@ -263,7 +263,7 @@ func (c *PostClient) Use(hooks ...Hook) { c.hooks.Post = append(c.hooks.Post, hooks...) } -// Create returns a create builder for Post. +// Create returns a builder for creating a Post entity. func (c *PostClient) Create() *PostCreate { mutation := newPostMutation(c.config, OpCreate) return &PostCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -298,12 +298,12 @@ func (c *PostClient) Delete() *PostDelete { return &PostDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *PostClient) DeleteOne(po *Post) *PostDeleteOne { return c.DeleteOneID(po.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *PostClient) DeleteOneID(id int) *PostDeleteOne { builder := c.Delete().Where(post.ID(id)) builder.mutation.id = &id @@ -385,7 +385,7 @@ func (c *UserClient) Use(hooks ...Hook) { c.hooks.User = append(c.hooks.User, hooks...) } -// Create returns a create builder for User. +// Create returns a builder for creating a User entity. func (c *UserClient) Create() *UserCreate { mutation := newUserMutation(c.config, OpCreate) return &UserCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -420,12 +420,12 @@ func (c *UserClient) Delete() *UserDelete { return &UserDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *UserClient) DeleteOne(u *User) *UserDeleteOne { return c.DeleteOneID(u.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *UserClient) DeleteOneID(id int) *UserDeleteOne { builder := c.Delete().Where(user.ID(id)) builder.mutation.id = &id diff --git a/entc/integration/cascadelete/ent/comment.go b/entc/integration/cascadelete/ent/comment.go index 06db44d4ec..1fcd7c8757 100644 --- a/entc/integration/cascadelete/ent/comment.go +++ b/entc/integration/cascadelete/ent/comment.go @@ -126,10 +126,11 @@ func (c *Comment) Unwrap() *Comment { func (c *Comment) String() string { var builder strings.Builder builder.WriteString("Comment(") - builder.WriteString(fmt.Sprintf("id=%v", c.ID)) - builder.WriteString(", text=") + builder.WriteString(fmt.Sprintf("id=%v, ", c.ID)) + builder.WriteString("text=") builder.WriteString(c.Text) - builder.WriteString(", post_id=") + builder.WriteString(", ") + builder.WriteString("post_id=") builder.WriteString(fmt.Sprintf("%v", c.PostID)) builder.WriteByte(')') return builder.String() diff --git a/entc/integration/cascadelete/ent/comment_create.go b/entc/integration/cascadelete/ent/comment_create.go index bc966c7bcf..4fa29bf2c4 100644 --- a/entc/integration/cascadelete/ent/comment_create.go +++ b/entc/integration/cascadelete/ent/comment_create.go @@ -224,11 +224,11 @@ func (ccb *CommentCreateBulk) Save(ctx context.Context) ([]*Comment, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/entc/integration/cascadelete/ent/post.go b/entc/integration/cascadelete/ent/post.go index d4f57a29ec..eb0426cd79 100644 --- a/entc/integration/cascadelete/ent/post.go +++ b/entc/integration/cascadelete/ent/post.go @@ -142,10 +142,11 @@ func (po *Post) Unwrap() *Post { func (po *Post) String() string { var builder strings.Builder builder.WriteString("Post(") - builder.WriteString(fmt.Sprintf("id=%v", po.ID)) - builder.WriteString(", text=") + builder.WriteString(fmt.Sprintf("id=%v, ", po.ID)) + builder.WriteString("text=") builder.WriteString(po.Text) - builder.WriteString(", author_id=") + builder.WriteString(", ") + builder.WriteString("author_id=") builder.WriteString(fmt.Sprintf("%v", po.AuthorID)) builder.WriteByte(')') return builder.String() diff --git a/entc/integration/cascadelete/ent/post_create.go b/entc/integration/cascadelete/ent/post_create.go index 48a66624a6..708671d046 100644 --- a/entc/integration/cascadelete/ent/post_create.go +++ b/entc/integration/cascadelete/ent/post_create.go @@ -279,11 +279,11 @@ func (pcb *PostCreateBulk) Save(ctx context.Context) ([]*Post, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/entc/integration/cascadelete/ent/user.go b/entc/integration/cascadelete/ent/user.go index c2975e00df..b79d95481d 100644 --- a/entc/integration/cascadelete/ent/user.go +++ b/entc/integration/cascadelete/ent/user.go @@ -112,8 +112,8 @@ func (u *User) Unwrap() *User { func (u *User) String() string { var builder strings.Builder builder.WriteString("User(") - builder.WriteString(fmt.Sprintf("id=%v", u.ID)) - builder.WriteString(", name=") + builder.WriteString(fmt.Sprintf("id=%v, ", u.ID)) + builder.WriteString("name=") builder.WriteString(u.Name) builder.WriteByte(')') return builder.String() diff --git a/entc/integration/cascadelete/ent/user_create.go b/entc/integration/cascadelete/ent/user_create.go index 08e1101eca..7ac022983a 100644 --- a/entc/integration/cascadelete/ent/user_create.go +++ b/entc/integration/cascadelete/ent/user_create.go @@ -239,11 +239,11 @@ func (ucb *UserCreateBulk) Save(ctx context.Context) ([]*User, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/entc/integration/config/ent/client.go b/entc/integration/config/ent/client.go index 054c7fc2b5..fcdd8c821d 100644 --- a/entc/integration/config/ent/client.go +++ b/entc/integration/config/ent/client.go @@ -142,7 +142,7 @@ func (c *UserClient) Use(hooks ...Hook) { c.hooks.User = append(c.hooks.User, hooks...) } -// Create returns a create builder for User. +// Create returns a builder for creating a User entity. func (c *UserClient) Create() *UserCreate { mutation := newUserMutation(c.config, OpCreate) return &UserCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -177,12 +177,12 @@ func (c *UserClient) Delete() *UserDelete { return &UserDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *UserClient) DeleteOne(u *User) *UserDeleteOne { return c.DeleteOneID(u.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *UserClient) DeleteOneID(id int) *UserDeleteOne { builder := c.Delete().Where(user.ID(id)) builder.mutation.id = &id diff --git a/entc/integration/config/ent/user.go b/entc/integration/config/ent/user.go index 4d0fccd582..5b249d8f5e 100644 --- a/entc/integration/config/ent/user.go +++ b/entc/integration/config/ent/user.go @@ -96,10 +96,11 @@ func (u *User) Unwrap() *User { func (u *User) String() string { var builder strings.Builder builder.WriteString("User(") - builder.WriteString(fmt.Sprintf("id=%v", u.ID)) - builder.WriteString(", name=") + builder.WriteString(fmt.Sprintf("id=%v, ", u.ID)) + builder.WriteString("name=") builder.WriteString(u.Name) - builder.WriteString(", label=") + builder.WriteString(", ") + builder.WriteString("label=") builder.WriteString(u.Label) builder.WriteByte(')') return builder.String() diff --git a/entc/integration/config/ent/user_create.go b/entc/integration/config/ent/user_create.go index d2d2297e09..4b71488ad5 100644 --- a/entc/integration/config/ent/user_create.go +++ b/entc/integration/config/ent/user_create.go @@ -224,11 +224,11 @@ func (ucb *UserCreateBulk) Save(ctx context.Context) ([]*User, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil && nodes[i].ID == 0 { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/entc/integration/customid/ent/account.go b/entc/integration/customid/ent/account.go index 16b5e103a9..ec2fd047c3 100644 --- a/entc/integration/customid/ent/account.go +++ b/entc/integration/customid/ent/account.go @@ -113,8 +113,8 @@ func (a *Account) Unwrap() *Account { func (a *Account) String() string { var builder strings.Builder builder.WriteString("Account(") - builder.WriteString(fmt.Sprintf("id=%v", a.ID)) - builder.WriteString(", email=") + builder.WriteString(fmt.Sprintf("id=%v, ", a.ID)) + builder.WriteString("email=") builder.WriteString(a.Email) builder.WriteByte(')') return builder.String() diff --git a/entc/integration/customid/ent/blob.go b/entc/integration/customid/ent/blob.go index 3d4c5aa9e3..51e655b46d 100644 --- a/entc/integration/customid/ent/blob.go +++ b/entc/integration/customid/ent/blob.go @@ -152,10 +152,11 @@ func (b *Blob) Unwrap() *Blob { func (b *Blob) String() string { var builder strings.Builder builder.WriteString("Blob(") - builder.WriteString(fmt.Sprintf("id=%v", b.ID)) - builder.WriteString(", uuid=") + builder.WriteString(fmt.Sprintf("id=%v, ", b.ID)) + builder.WriteString("uuid=") builder.WriteString(fmt.Sprintf("%v", b.UUID)) - builder.WriteString(", count=") + builder.WriteString(", ") + builder.WriteString("count=") builder.WriteString(fmt.Sprintf("%v", b.Count)) builder.WriteByte(')') return builder.String() diff --git a/entc/integration/customid/ent/car.go b/entc/integration/customid/ent/car.go index 8826f6674c..3a7937e455 100644 --- a/entc/integration/customid/ent/car.go +++ b/entc/integration/customid/ent/car.go @@ -146,12 +146,14 @@ func (c *Car) Unwrap() *Car { func (c *Car) String() string { var builder strings.Builder builder.WriteString("Car(") - builder.WriteString(fmt.Sprintf("id=%v", c.ID)) - builder.WriteString(", before_id=") + builder.WriteString(fmt.Sprintf("id=%v, ", c.ID)) + builder.WriteString("before_id=") builder.WriteString(fmt.Sprintf("%v", c.BeforeID)) - builder.WriteString(", after_id=") + builder.WriteString(", ") + builder.WriteString("after_id=") builder.WriteString(fmt.Sprintf("%v", c.AfterID)) - builder.WriteString(", model=") + builder.WriteString(", ") + builder.WriteString("model=") builder.WriteString(c.Model) builder.WriteByte(')') return builder.String() diff --git a/entc/integration/customid/ent/car_create.go b/entc/integration/customid/ent/car_create.go index 9c272f5507..5f333701ce 100644 --- a/entc/integration/customid/ent/car_create.go +++ b/entc/integration/customid/ent/car_create.go @@ -566,11 +566,11 @@ func (ccb *CarCreateBulk) Save(ctx context.Context) ([]*Car, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil && nodes[i].ID == 0 { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/entc/integration/customid/ent/client.go b/entc/integration/customid/ent/client.go index d5c548e30c..95a0507a67 100644 --- a/entc/integration/customid/ent/client.go +++ b/entc/integration/customid/ent/client.go @@ -237,7 +237,7 @@ func (c *AccountClient) Use(hooks ...Hook) { c.hooks.Account = append(c.hooks.Account, hooks...) } -// Create returns a create builder for Account. +// Create returns a builder for creating a Account entity. func (c *AccountClient) Create() *AccountCreate { mutation := newAccountMutation(c.config, OpCreate) return &AccountCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -272,12 +272,12 @@ func (c *AccountClient) Delete() *AccountDelete { return &AccountDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *AccountClient) DeleteOne(a *Account) *AccountDeleteOne { return c.DeleteOneID(a.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *AccountClient) DeleteOneID(id sid.ID) *AccountDeleteOne { builder := c.Delete().Where(account.ID(id)) builder.mutation.id = &id @@ -343,7 +343,7 @@ func (c *BlobClient) Use(hooks ...Hook) { c.hooks.Blob = append(c.hooks.Blob, hooks...) } -// Create returns a create builder for Blob. +// Create returns a builder for creating a Blob entity. func (c *BlobClient) Create() *BlobCreate { mutation := newBlobMutation(c.config, OpCreate) return &BlobCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -378,12 +378,12 @@ func (c *BlobClient) Delete() *BlobDelete { return &BlobDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *BlobClient) DeleteOne(b *Blob) *BlobDeleteOne { return c.DeleteOneID(b.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *BlobClient) DeleteOneID(id uuid.UUID) *BlobDeleteOne { builder := c.Delete().Where(blob.ID(id)) builder.mutation.id = &id @@ -465,7 +465,7 @@ func (c *CarClient) Use(hooks ...Hook) { c.hooks.Car = append(c.hooks.Car, hooks...) } -// Create returns a create builder for Car. +// Create returns a builder for creating a Car entity. func (c *CarClient) Create() *CarCreate { mutation := newCarMutation(c.config, OpCreate) return &CarCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -500,12 +500,12 @@ func (c *CarClient) Delete() *CarDelete { return &CarDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *CarClient) DeleteOne(ca *Car) *CarDeleteOne { return c.DeleteOneID(ca.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *CarClient) DeleteOneID(id int) *CarDeleteOne { builder := c.Delete().Where(car.ID(id)) builder.mutation.id = &id @@ -571,7 +571,7 @@ func (c *DeviceClient) Use(hooks ...Hook) { c.hooks.Device = append(c.hooks.Device, hooks...) } -// Create returns a create builder for Device. +// Create returns a builder for creating a Device entity. func (c *DeviceClient) Create() *DeviceCreate { mutation := newDeviceMutation(c.config, OpCreate) return &DeviceCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -606,12 +606,12 @@ func (c *DeviceClient) Delete() *DeviceDelete { return &DeviceDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *DeviceClient) DeleteOne(d *Device) *DeviceDeleteOne { return c.DeleteOneID(d.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *DeviceClient) DeleteOneID(id schema.ID) *DeviceDeleteOne { builder := c.Delete().Where(device.ID(id)) builder.mutation.id = &id @@ -693,7 +693,7 @@ func (c *DocClient) Use(hooks ...Hook) { c.hooks.Doc = append(c.hooks.Doc, hooks...) } -// Create returns a create builder for Doc. +// Create returns a builder for creating a Doc entity. func (c *DocClient) Create() *DocCreate { mutation := newDocMutation(c.config, OpCreate) return &DocCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -728,12 +728,12 @@ func (c *DocClient) Delete() *DocDelete { return &DocDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *DocClient) DeleteOne(d *Doc) *DocDeleteOne { return c.DeleteOneID(d.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *DocClient) DeleteOneID(id schema.DocID) *DocDeleteOne { builder := c.Delete().Where(doc.ID(id)) builder.mutation.id = &id @@ -815,7 +815,7 @@ func (c *GroupClient) Use(hooks ...Hook) { c.hooks.Group = append(c.hooks.Group, hooks...) } -// Create returns a create builder for Group. +// Create returns a builder for creating a Group entity. func (c *GroupClient) Create() *GroupCreate { mutation := newGroupMutation(c.config, OpCreate) return &GroupCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -850,12 +850,12 @@ func (c *GroupClient) Delete() *GroupDelete { return &GroupDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *GroupClient) DeleteOne(gr *Group) *GroupDeleteOne { return c.DeleteOneID(gr.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *GroupClient) DeleteOneID(id int) *GroupDeleteOne { builder := c.Delete().Where(group.ID(id)) builder.mutation.id = &id @@ -921,7 +921,7 @@ func (c *MixinIDClient) Use(hooks ...Hook) { c.hooks.MixinID = append(c.hooks.MixinID, hooks...) } -// Create returns a create builder for MixinID. +// Create returns a builder for creating a MixinID entity. func (c *MixinIDClient) Create() *MixinIDCreate { mutation := newMixinIDMutation(c.config, OpCreate) return &MixinIDCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -956,12 +956,12 @@ func (c *MixinIDClient) Delete() *MixinIDDelete { return &MixinIDDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *MixinIDClient) DeleteOne(mi *MixinID) *MixinIDDeleteOne { return c.DeleteOneID(mi.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *MixinIDClient) DeleteOneID(id uuid.UUID) *MixinIDDeleteOne { builder := c.Delete().Where(mixinid.ID(id)) builder.mutation.id = &id @@ -1011,7 +1011,7 @@ func (c *NoteClient) Use(hooks ...Hook) { c.hooks.Note = append(c.hooks.Note, hooks...) } -// Create returns a create builder for Note. +// Create returns a builder for creating a Note entity. func (c *NoteClient) Create() *NoteCreate { mutation := newNoteMutation(c.config, OpCreate) return &NoteCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -1046,12 +1046,12 @@ func (c *NoteClient) Delete() *NoteDelete { return &NoteDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *NoteClient) DeleteOne(n *Note) *NoteDeleteOne { return c.DeleteOneID(n.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *NoteClient) DeleteOneID(id schema.NoteID) *NoteDeleteOne { builder := c.Delete().Where(note.ID(id)) builder.mutation.id = &id @@ -1133,7 +1133,7 @@ func (c *OtherClient) Use(hooks ...Hook) { c.hooks.Other = append(c.hooks.Other, hooks...) } -// Create returns a create builder for Other. +// Create returns a builder for creating a Other entity. func (c *OtherClient) Create() *OtherCreate { mutation := newOtherMutation(c.config, OpCreate) return &OtherCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -1168,12 +1168,12 @@ func (c *OtherClient) Delete() *OtherDelete { return &OtherDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *OtherClient) DeleteOne(o *Other) *OtherDeleteOne { return c.DeleteOneID(o.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *OtherClient) DeleteOneID(id sid.ID) *OtherDeleteOne { builder := c.Delete().Where(other.ID(id)) builder.mutation.id = &id @@ -1223,7 +1223,7 @@ func (c *PetClient) Use(hooks ...Hook) { c.hooks.Pet = append(c.hooks.Pet, hooks...) } -// Create returns a create builder for Pet. +// Create returns a builder for creating a Pet entity. func (c *PetClient) Create() *PetCreate { mutation := newPetMutation(c.config, OpCreate) return &PetCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -1258,12 +1258,12 @@ func (c *PetClient) Delete() *PetDelete { return &PetDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *PetClient) DeleteOne(pe *Pet) *PetDeleteOne { return c.DeleteOneID(pe.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *PetClient) DeleteOneID(id string) *PetDeleteOne { builder := c.Delete().Where(pet.ID(id)) builder.mutation.id = &id @@ -1377,7 +1377,7 @@ func (c *RevisionClient) Use(hooks ...Hook) { c.hooks.Revision = append(c.hooks.Revision, hooks...) } -// Create returns a create builder for Revision. +// Create returns a builder for creating a Revision entity. func (c *RevisionClient) Create() *RevisionCreate { mutation := newRevisionMutation(c.config, OpCreate) return &RevisionCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -1412,12 +1412,12 @@ func (c *RevisionClient) Delete() *RevisionDelete { return &RevisionDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *RevisionClient) DeleteOne(r *Revision) *RevisionDeleteOne { return c.DeleteOneID(r.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *RevisionClient) DeleteOneID(id string) *RevisionDeleteOne { builder := c.Delete().Where(revision.ID(id)) builder.mutation.id = &id @@ -1467,7 +1467,7 @@ func (c *SessionClient) Use(hooks ...Hook) { c.hooks.Session = append(c.hooks.Session, hooks...) } -// Create returns a create builder for Session. +// Create returns a builder for creating a Session entity. func (c *SessionClient) Create() *SessionCreate { mutation := newSessionMutation(c.config, OpCreate) return &SessionCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -1502,12 +1502,12 @@ func (c *SessionClient) Delete() *SessionDelete { return &SessionDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *SessionClient) DeleteOne(s *Session) *SessionDeleteOne { return c.DeleteOneID(s.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *SessionClient) DeleteOneID(id schema.ID) *SessionDeleteOne { builder := c.Delete().Where(session.ID(id)) builder.mutation.id = &id @@ -1573,7 +1573,7 @@ func (c *TokenClient) Use(hooks ...Hook) { c.hooks.Token = append(c.hooks.Token, hooks...) } -// Create returns a create builder for Token. +// Create returns a builder for creating a Token entity. func (c *TokenClient) Create() *TokenCreate { mutation := newTokenMutation(c.config, OpCreate) return &TokenCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -1608,12 +1608,12 @@ func (c *TokenClient) Delete() *TokenDelete { return &TokenDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *TokenClient) DeleteOne(t *Token) *TokenDeleteOne { return c.DeleteOneID(t.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *TokenClient) DeleteOneID(id sid.ID) *TokenDeleteOne { builder := c.Delete().Where(token.ID(id)) builder.mutation.id = &id @@ -1679,7 +1679,7 @@ func (c *UserClient) Use(hooks ...Hook) { c.hooks.User = append(c.hooks.User, hooks...) } -// Create returns a create builder for User. +// Create returns a builder for creating a User entity. func (c *UserClient) Create() *UserCreate { mutation := newUserMutation(c.config, OpCreate) return &UserCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -1714,12 +1714,12 @@ func (c *UserClient) Delete() *UserDelete { return &UserDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *UserClient) DeleteOne(u *User) *UserDeleteOne { return c.DeleteOneID(u.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *UserClient) DeleteOneID(id int) *UserDeleteOne { builder := c.Delete().Where(user.ID(id)) builder.mutation.id = &id diff --git a/entc/integration/customid/ent/doc.go b/entc/integration/customid/ent/doc.go index 94454ea41a..6a7420226d 100644 --- a/entc/integration/customid/ent/doc.go +++ b/entc/integration/customid/ent/doc.go @@ -144,8 +144,8 @@ func (d *Doc) Unwrap() *Doc { func (d *Doc) String() string { var builder strings.Builder builder.WriteString("Doc(") - builder.WriteString(fmt.Sprintf("id=%v", d.ID)) - builder.WriteString(", text=") + builder.WriteString(fmt.Sprintf("id=%v, ", d.ID)) + builder.WriteString("text=") builder.WriteString(d.Text) builder.WriteByte(')') return builder.String() diff --git a/entc/integration/customid/ent/group_create.go b/entc/integration/customid/ent/group_create.go index aabacb7e86..4da427e24d 100644 --- a/entc/integration/customid/ent/group_create.go +++ b/entc/integration/customid/ent/group_create.go @@ -349,11 +349,11 @@ func (gcb *GroupCreateBulk) Save(ctx context.Context) ([]*Group, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil && nodes[i].ID == 0 { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/entc/integration/customid/ent/mixinid.go b/entc/integration/customid/ent/mixinid.go index 144fd6606c..801ff20688 100644 --- a/entc/integration/customid/ent/mixinid.go +++ b/entc/integration/customid/ent/mixinid.go @@ -95,10 +95,11 @@ func (mi *MixinID) Unwrap() *MixinID { func (mi *MixinID) String() string { var builder strings.Builder builder.WriteString("MixinID(") - builder.WriteString(fmt.Sprintf("id=%v", mi.ID)) - builder.WriteString(", some_field=") + builder.WriteString(fmt.Sprintf("id=%v, ", mi.ID)) + builder.WriteString("some_field=") builder.WriteString(mi.SomeField) - builder.WriteString(", mixin_field=") + builder.WriteString(", ") + builder.WriteString("mixin_field=") builder.WriteString(mi.MixinField) builder.WriteByte(')') return builder.String() diff --git a/entc/integration/customid/ent/note.go b/entc/integration/customid/ent/note.go index f8be2ce780..5c404f423f 100644 --- a/entc/integration/customid/ent/note.go +++ b/entc/integration/customid/ent/note.go @@ -142,8 +142,8 @@ func (n *Note) Unwrap() *Note { func (n *Note) String() string { var builder strings.Builder builder.WriteString("Note(") - builder.WriteString(fmt.Sprintf("id=%v", n.ID)) - builder.WriteString(", text=") + builder.WriteString(fmt.Sprintf("id=%v, ", n.ID)) + builder.WriteString("text=") builder.WriteString(n.Text) builder.WriteByte(')') return builder.String() diff --git a/entc/integration/customid/ent/token.go b/entc/integration/customid/ent/token.go index c9a8369266..2e363a830a 100644 --- a/entc/integration/customid/ent/token.go +++ b/entc/integration/customid/ent/token.go @@ -129,8 +129,8 @@ func (t *Token) Unwrap() *Token { func (t *Token) String() string { var builder strings.Builder builder.WriteString("Token(") - builder.WriteString(fmt.Sprintf("id=%v", t.ID)) - builder.WriteString(", body=") + builder.WriteString(fmt.Sprintf("id=%v, ", t.ID)) + builder.WriteString("body=") builder.WriteString(t.Body) builder.WriteByte(')') return builder.String() diff --git a/entc/integration/customid/ent/user_create.go b/entc/integration/customid/ent/user_create.go index 117c1e6dcc..5837713510 100644 --- a/entc/integration/customid/ent/user_create.go +++ b/entc/integration/customid/ent/user_create.go @@ -457,11 +457,11 @@ func (ucb *UserCreateBulk) Save(ctx context.Context) ([]*User, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil && nodes[i].ID == 0 { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/entc/integration/edgefield/ent/car.go b/entc/integration/edgefield/ent/car.go index 8e02151182..ceb9760311 100644 --- a/entc/integration/edgefield/ent/car.go +++ b/entc/integration/edgefield/ent/car.go @@ -113,8 +113,8 @@ func (c *Car) Unwrap() *Car { func (c *Car) String() string { var builder strings.Builder builder.WriteString("Car(") - builder.WriteString(fmt.Sprintf("id=%v", c.ID)) - builder.WriteString(", number=") + builder.WriteString(fmt.Sprintf("id=%v, ", c.ID)) + builder.WriteString("number=") builder.WriteString(c.Number) builder.WriteByte(')') return builder.String() diff --git a/entc/integration/edgefield/ent/card.go b/entc/integration/edgefield/ent/card.go index 0d89ba3e81..2d1a270d67 100644 --- a/entc/integration/edgefield/ent/card.go +++ b/entc/integration/edgefield/ent/card.go @@ -126,10 +126,11 @@ func (c *Card) Unwrap() *Card { func (c *Card) String() string { var builder strings.Builder builder.WriteString("Card(") - builder.WriteString(fmt.Sprintf("id=%v", c.ID)) - builder.WriteString(", number=") + builder.WriteString(fmt.Sprintf("id=%v, ", c.ID)) + builder.WriteString("number=") builder.WriteString(c.Number) - builder.WriteString(", owner_id=") + builder.WriteString(", ") + builder.WriteString("owner_id=") builder.WriteString(fmt.Sprintf("%v", c.OwnerID)) builder.WriteByte(')') return builder.String() diff --git a/entc/integration/edgefield/ent/card_create.go b/entc/integration/edgefield/ent/card_create.go index 59992deca2..f68764bf21 100644 --- a/entc/integration/edgefield/ent/card_create.go +++ b/entc/integration/edgefield/ent/card_create.go @@ -230,11 +230,11 @@ func (ccb *CardCreateBulk) Save(ctx context.Context) ([]*Card, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/entc/integration/edgefield/ent/client.go b/entc/integration/edgefield/ent/client.go index b7260fe32a..e69a7e0edc 100644 --- a/entc/integration/edgefield/ent/client.go +++ b/entc/integration/edgefield/ent/client.go @@ -200,7 +200,7 @@ func (c *CarClient) Use(hooks ...Hook) { c.hooks.Car = append(c.hooks.Car, hooks...) } -// Create returns a create builder for Car. +// Create returns a builder for creating a Car entity. func (c *CarClient) Create() *CarCreate { mutation := newCarMutation(c.config, OpCreate) return &CarCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -235,12 +235,12 @@ func (c *CarClient) Delete() *CarDelete { return &CarDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *CarClient) DeleteOne(ca *Car) *CarDeleteOne { return c.DeleteOneID(ca.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *CarClient) DeleteOneID(id uuid.UUID) *CarDeleteOne { builder := c.Delete().Where(car.ID(id)) builder.mutation.id = &id @@ -306,7 +306,7 @@ func (c *CardClient) Use(hooks ...Hook) { c.hooks.Card = append(c.hooks.Card, hooks...) } -// Create returns a create builder for Card. +// Create returns a builder for creating a Card entity. func (c *CardClient) Create() *CardCreate { mutation := newCardMutation(c.config, OpCreate) return &CardCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -341,12 +341,12 @@ func (c *CardClient) Delete() *CardDelete { return &CardDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *CardClient) DeleteOne(ca *Card) *CardDeleteOne { return c.DeleteOneID(ca.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *CardClient) DeleteOneID(id int) *CardDeleteOne { builder := c.Delete().Where(card.ID(id)) builder.mutation.id = &id @@ -412,7 +412,7 @@ func (c *InfoClient) Use(hooks ...Hook) { c.hooks.Info = append(c.hooks.Info, hooks...) } -// Create returns a create builder for Info. +// Create returns a builder for creating a Info entity. func (c *InfoClient) Create() *InfoCreate { mutation := newInfoMutation(c.config, OpCreate) return &InfoCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -447,12 +447,12 @@ func (c *InfoClient) Delete() *InfoDelete { return &InfoDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *InfoClient) DeleteOne(i *Info) *InfoDeleteOne { return c.DeleteOneID(i.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *InfoClient) DeleteOneID(id int) *InfoDeleteOne { builder := c.Delete().Where(info.ID(id)) builder.mutation.id = &id @@ -518,7 +518,7 @@ func (c *MetadataClient) Use(hooks ...Hook) { c.hooks.Metadata = append(c.hooks.Metadata, hooks...) } -// Create returns a create builder for Metadata. +// Create returns a builder for creating a Metadata entity. func (c *MetadataClient) Create() *MetadataCreate { mutation := newMetadataMutation(c.config, OpCreate) return &MetadataCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -553,12 +553,12 @@ func (c *MetadataClient) Delete() *MetadataDelete { return &MetadataDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *MetadataClient) DeleteOne(m *Metadata) *MetadataDeleteOne { return c.DeleteOneID(m.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *MetadataClient) DeleteOneID(id int) *MetadataDeleteOne { builder := c.Delete().Where(metadata.ID(id)) builder.mutation.id = &id @@ -656,7 +656,7 @@ func (c *NodeClient) Use(hooks ...Hook) { c.hooks.Node = append(c.hooks.Node, hooks...) } -// Create returns a create builder for Node. +// Create returns a builder for creating a Node entity. func (c *NodeClient) Create() *NodeCreate { mutation := newNodeMutation(c.config, OpCreate) return &NodeCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -691,12 +691,12 @@ func (c *NodeClient) Delete() *NodeDelete { return &NodeDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *NodeClient) DeleteOne(n *Node) *NodeDeleteOne { return c.DeleteOneID(n.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *NodeClient) DeleteOneID(id int) *NodeDeleteOne { builder := c.Delete().Where(node.ID(id)) builder.mutation.id = &id @@ -778,7 +778,7 @@ func (c *PetClient) Use(hooks ...Hook) { c.hooks.Pet = append(c.hooks.Pet, hooks...) } -// Create returns a create builder for Pet. +// Create returns a builder for creating a Pet entity. func (c *PetClient) Create() *PetCreate { mutation := newPetMutation(c.config, OpCreate) return &PetCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -813,12 +813,12 @@ func (c *PetClient) Delete() *PetDelete { return &PetDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *PetClient) DeleteOne(pe *Pet) *PetDeleteOne { return c.DeleteOneID(pe.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *PetClient) DeleteOneID(id int) *PetDeleteOne { builder := c.Delete().Where(pet.ID(id)) builder.mutation.id = &id @@ -884,7 +884,7 @@ func (c *PostClient) Use(hooks ...Hook) { c.hooks.Post = append(c.hooks.Post, hooks...) } -// Create returns a create builder for Post. +// Create returns a builder for creating a Post entity. func (c *PostClient) Create() *PostCreate { mutation := newPostMutation(c.config, OpCreate) return &PostCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -919,12 +919,12 @@ func (c *PostClient) Delete() *PostDelete { return &PostDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *PostClient) DeleteOne(po *Post) *PostDeleteOne { return c.DeleteOneID(po.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *PostClient) DeleteOneID(id int) *PostDeleteOne { builder := c.Delete().Where(post.ID(id)) builder.mutation.id = &id @@ -990,7 +990,7 @@ func (c *RentalClient) Use(hooks ...Hook) { c.hooks.Rental = append(c.hooks.Rental, hooks...) } -// Create returns a create builder for Rental. +// Create returns a builder for creating a Rental entity. func (c *RentalClient) Create() *RentalCreate { mutation := newRentalMutation(c.config, OpCreate) return &RentalCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -1025,12 +1025,12 @@ func (c *RentalClient) Delete() *RentalDelete { return &RentalDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *RentalClient) DeleteOne(r *Rental) *RentalDeleteOne { return c.DeleteOneID(r.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *RentalClient) DeleteOneID(id int) *RentalDeleteOne { builder := c.Delete().Where(rental.ID(id)) builder.mutation.id = &id @@ -1112,7 +1112,7 @@ func (c *UserClient) Use(hooks ...Hook) { c.hooks.User = append(c.hooks.User, hooks...) } -// Create returns a create builder for User. +// Create returns a builder for creating a User entity. func (c *UserClient) Create() *UserCreate { mutation := newUserMutation(c.config, OpCreate) return &UserCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -1147,12 +1147,12 @@ func (c *UserClient) Delete() *UserDelete { return &UserDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *UserClient) DeleteOne(u *User) *UserDeleteOne { return c.DeleteOneID(u.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *UserClient) DeleteOneID(id int) *UserDeleteOne { builder := c.Delete().Where(user.ID(id)) builder.mutation.id = &id diff --git a/entc/integration/edgefield/ent/info.go b/entc/integration/edgefield/ent/info.go index 0abfe0b86c..47f8c05da4 100644 --- a/entc/integration/edgefield/ent/info.go +++ b/entc/integration/edgefield/ent/info.go @@ -121,8 +121,8 @@ func (i *Info) Unwrap() *Info { func (i *Info) String() string { var builder strings.Builder builder.WriteString("Info(") - builder.WriteString(fmt.Sprintf("id=%v", i.ID)) - builder.WriteString(", content=") + builder.WriteString(fmt.Sprintf("id=%v, ", i.ID)) + builder.WriteString("content=") builder.WriteString(fmt.Sprintf("%v", i.Content)) builder.WriteByte(')') return builder.String() diff --git a/entc/integration/edgefield/ent/info_create.go b/entc/integration/edgefield/ent/info_create.go index c62d9cefc7..e14a43ef97 100644 --- a/entc/integration/edgefield/ent/info_create.go +++ b/entc/integration/edgefield/ent/info_create.go @@ -239,11 +239,11 @@ func (icb *InfoCreateBulk) Save(ctx context.Context) ([]*Info, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil && nodes[i].ID == 0 { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/entc/integration/edgefield/ent/metadata.go b/entc/integration/edgefield/ent/metadata.go index bd421d9d4d..ab2ecd85bc 100644 --- a/entc/integration/edgefield/ent/metadata.go +++ b/entc/integration/edgefield/ent/metadata.go @@ -161,10 +161,11 @@ func (m *Metadata) Unwrap() *Metadata { func (m *Metadata) String() string { var builder strings.Builder builder.WriteString("Metadata(") - builder.WriteString(fmt.Sprintf("id=%v", m.ID)) - builder.WriteString(", age=") + builder.WriteString(fmt.Sprintf("id=%v, ", m.ID)) + builder.WriteString("age=") builder.WriteString(fmt.Sprintf("%v", m.Age)) - builder.WriteString(", parent_id=") + builder.WriteString(", ") + builder.WriteString("parent_id=") builder.WriteString(fmt.Sprintf("%v", m.ParentID)) builder.WriteByte(')') return builder.String() diff --git a/entc/integration/edgefield/ent/metadata_create.go b/entc/integration/edgefield/ent/metadata_create.go index 5c48a13ec5..2390cfb528 100644 --- a/entc/integration/edgefield/ent/metadata_create.go +++ b/entc/integration/edgefield/ent/metadata_create.go @@ -329,11 +329,11 @@ func (mcb *MetadataCreateBulk) Save(ctx context.Context) ([]*Metadata, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil && nodes[i].ID == 0 { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/entc/integration/edgefield/ent/node.go b/entc/integration/edgefield/ent/node.go index ca8c9b6736..38b02eca95 100644 --- a/entc/integration/edgefield/ent/node.go +++ b/entc/integration/edgefield/ent/node.go @@ -144,10 +144,11 @@ func (n *Node) Unwrap() *Node { func (n *Node) String() string { var builder strings.Builder builder.WriteString("Node(") - builder.WriteString(fmt.Sprintf("id=%v", n.ID)) - builder.WriteString(", value=") + builder.WriteString(fmt.Sprintf("id=%v, ", n.ID)) + builder.WriteString("value=") builder.WriteString(fmt.Sprintf("%v", n.Value)) - builder.WriteString(", prev_id=") + builder.WriteString(", ") + builder.WriteString("prev_id=") builder.WriteString(fmt.Sprintf("%v", n.PrevID)) builder.WriteByte(')') return builder.String() diff --git a/entc/integration/edgefield/ent/node_create.go b/entc/integration/edgefield/ent/node_create.go index a14f28fb6a..609e889004 100644 --- a/entc/integration/edgefield/ent/node_create.go +++ b/entc/integration/edgefield/ent/node_create.go @@ -281,11 +281,11 @@ func (ncb *NodeCreateBulk) Save(ctx context.Context) ([]*Node, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/entc/integration/edgefield/ent/pet.go b/entc/integration/edgefield/ent/pet.go index b413cae29e..57b8bec5f1 100644 --- a/entc/integration/edgefield/ent/pet.go +++ b/entc/integration/edgefield/ent/pet.go @@ -116,8 +116,8 @@ func (pe *Pet) Unwrap() *Pet { func (pe *Pet) String() string { var builder strings.Builder builder.WriteString("Pet(") - builder.WriteString(fmt.Sprintf("id=%v", pe.ID)) - builder.WriteString(", owner_id=") + builder.WriteString(fmt.Sprintf("id=%v, ", pe.ID)) + builder.WriteString("owner_id=") builder.WriteString(fmt.Sprintf("%v", pe.OwnerID)) builder.WriteByte(')') return builder.String() diff --git a/entc/integration/edgefield/ent/pet_create.go b/entc/integration/edgefield/ent/pet_create.go index 774f2f80b7..04888d860c 100644 --- a/entc/integration/edgefield/ent/pet_create.go +++ b/entc/integration/edgefield/ent/pet_create.go @@ -208,11 +208,11 @@ func (pcb *PetCreateBulk) Save(ctx context.Context) ([]*Pet, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/entc/integration/edgefield/ent/post.go b/entc/integration/edgefield/ent/post.go index 9bfcbf37eb..70cdb86d32 100644 --- a/entc/integration/edgefield/ent/post.go +++ b/entc/integration/edgefield/ent/post.go @@ -127,11 +127,12 @@ func (po *Post) Unwrap() *Post { func (po *Post) String() string { var builder strings.Builder builder.WriteString("Post(") - builder.WriteString(fmt.Sprintf("id=%v", po.ID)) - builder.WriteString(", text=") + builder.WriteString(fmt.Sprintf("id=%v, ", po.ID)) + builder.WriteString("text=") builder.WriteString(po.Text) + builder.WriteString(", ") if v := po.AuthorID; v != nil { - builder.WriteString(", author_id=") + builder.WriteString("author_id=") builder.WriteString(fmt.Sprintf("%v", *v)) } builder.WriteByte(')') diff --git a/entc/integration/edgefield/ent/post_create.go b/entc/integration/edgefield/ent/post_create.go index f19f1d28da..ce736a9d8b 100644 --- a/entc/integration/edgefield/ent/post_create.go +++ b/entc/integration/edgefield/ent/post_create.go @@ -226,11 +226,11 @@ func (pcb *PostCreateBulk) Save(ctx context.Context) ([]*Post, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/entc/integration/edgefield/ent/rental.go b/entc/integration/edgefield/ent/rental.go index 111d3a5a33..d69334c1c3 100644 --- a/entc/integration/edgefield/ent/rental.go +++ b/entc/integration/edgefield/ent/rental.go @@ -160,12 +160,14 @@ func (r *Rental) Unwrap() *Rental { func (r *Rental) String() string { var builder strings.Builder builder.WriteString("Rental(") - builder.WriteString(fmt.Sprintf("id=%v", r.ID)) - builder.WriteString(", date=") + builder.WriteString(fmt.Sprintf("id=%v, ", r.ID)) + builder.WriteString("date=") builder.WriteString(r.Date.Format(time.ANSIC)) - builder.WriteString(", user_id=") + builder.WriteString(", ") + builder.WriteString("user_id=") builder.WriteString(fmt.Sprintf("%v", r.UserID)) - builder.WriteString(", car_id=") + builder.WriteString(", ") + builder.WriteString("car_id=") builder.WriteString(fmt.Sprintf("%v", r.CarID)) builder.WriteByte(')') return builder.String() diff --git a/entc/integration/edgefield/ent/rental_create.go b/entc/integration/edgefield/ent/rental_create.go index 57445a6e63..542b8fb0b7 100644 --- a/entc/integration/edgefield/ent/rental_create.go +++ b/entc/integration/edgefield/ent/rental_create.go @@ -282,11 +282,11 @@ func (rcb *RentalCreateBulk) Save(ctx context.Context) ([]*Rental, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/entc/integration/edgefield/ent/user.go b/entc/integration/edgefield/ent/user.go index a48c2930cf..e4e0968058 100644 --- a/entc/integration/edgefield/ent/user.go +++ b/entc/integration/edgefield/ent/user.go @@ -252,10 +252,11 @@ func (u *User) Unwrap() *User { func (u *User) String() string { var builder strings.Builder builder.WriteString("User(") - builder.WriteString(fmt.Sprintf("id=%v", u.ID)) - builder.WriteString(", parent_id=") + builder.WriteString(fmt.Sprintf("id=%v, ", u.ID)) + builder.WriteString("parent_id=") builder.WriteString(fmt.Sprintf("%v", u.ParentID)) - builder.WriteString(", spouse_id=") + builder.WriteString(", ") + builder.WriteString("spouse_id=") builder.WriteString(fmt.Sprintf("%v", u.SpouseID)) builder.WriteByte(')') return builder.String() diff --git a/entc/integration/edgefield/ent/user_create.go b/entc/integration/edgefield/ent/user_create.go index 3a441d06fe..1db6d52855 100644 --- a/entc/integration/edgefield/ent/user_create.go +++ b/entc/integration/edgefield/ent/user_create.go @@ -475,11 +475,11 @@ func (ucb *UserCreateBulk) Save(ctx context.Context) ([]*User, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil && nodes[i].ID == 0 { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/entc/integration/edgeschema/edgeschema_test.go b/entc/integration/edgeschema/edgeschema_test.go new file mode 100644 index 0000000000..6372c96f82 --- /dev/null +++ b/entc/integration/edgeschema/edgeschema_test.go @@ -0,0 +1,168 @@ +// 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 edgeschema + +import ( + "context" + "testing" + "time" + + "entgo.io/ent/dialect" + "entgo.io/ent/entc/integration/edgeschema/ent" + "entgo.io/ent/entc/integration/edgeschema/ent/friendship" + "entgo.io/ent/entc/integration/edgeschema/ent/group" + "entgo.io/ent/entc/integration/edgeschema/ent/migrate" + "entgo.io/ent/entc/integration/edgeschema/ent/relationship" + "entgo.io/ent/entc/integration/edgeschema/ent/tweetlike" + "entgo.io/ent/entc/integration/edgeschema/ent/user" + + _ "github.com/mattn/go-sqlite3" + "github.com/stretchr/testify/require" +) + +func TestEdgeSchemaWithID(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, migrate.WithGlobalUniqueID(true))) + + hub, lab := client.Group.Create().SetName("GitHub").SaveX(ctx), client.Group.Create().SetName("GitLab").SaveX(ctx) + a8m, nat := client.User.Create().SetName("a8m").AddGroups(hub, lab).SaveX(ctx), client.User.Create().SetName("nati").AddGroups(hub).SaveX(ctx) + require.Equal(t, 2, a8m.QueryGroups().CountX(ctx)) + require.Equal(t, 1, nat.QueryGroups().CountX(ctx)) + + edges := a8m.QueryJoinedGroups().AllX(ctx) + require.Equal(t, a8m.ID, edges[0].UserID) + require.Equal(t, hub.ID, edges[0].GroupID) + require.False(t, edges[0].JoinedAt.IsZero()) + require.Equal(t, a8m.ID, edges[1].UserID) + require.Equal(t, lab.ID, edges[1].GroupID) + require.False(t, edges[1].JoinedAt.IsZero()) + require.Equal(t, hub.ID, a8m.QueryJoinedGroups().QueryGroup().FirstIDX(ctx)) + require.Equal(t, lab.ID, a8m.QueryJoinedGroups().QueryGroup().Order(ent.Desc(group.FieldID)).FirstIDX(ctx)) + + edges = nat.QueryJoinedGroups().AllX(ctx) + require.Equal(t, nat.ID, edges[0].UserID) + require.Equal(t, hub.ID, edges[0].GroupID) + require.False(t, edges[0].JoinedAt.IsZero()) + + err = nat.Update().AddGroups(hub).Exec(ctx) + require.True(t, ent.IsConstraintError(err), "unique constraint failed: user_groups.user_id, user_groups.group_id") + + users := client.User.Query().WithJoinedGroups(func(q *ent.UserGroupQuery) { q.WithGroup() }).AllX(ctx) + require.Equal(t, []int{a8m.ID, nat.ID}, []int{users[0].ID, users[1].ID}) + require.Equal(t, []int{hub.ID, lab.ID}, []int{users[0].Edges.JoinedGroups[0].GroupID, users[0].Edges.JoinedGroups[1].GroupID}) + require.Equal(t, []int{hub.ID, lab.ID}, []int{users[0].Edges.JoinedGroups[0].Edges.Group.ID, users[0].Edges.JoinedGroups[1].Edges.Group.ID}) + require.Equal(t, hub.ID, users[1].Edges.JoinedGroups[0].GroupID) +} + +func TestEdgeSchemaCompositeID(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, migrate.WithGlobalUniqueID(true))) + + tweets := client.Tweet.CreateBulk( + client.Tweet.Create().SetText("foo"), + client.Tweet.Create().SetText("bar"), + client.Tweet.Create().SetText("baz"), + ).SaveX(ctx) + a8m := client.User.Create().SetName("a8m").AddLikedTweets(tweets[:2]...).SaveX(ctx) + nat := client.User.Create().SetName("nati").AddLikedTweets(tweets[0]).SaveX(ctx) + likes := a8m.QueryLikes().AllX(ctx) + require.Len(t, likes, 2) + require.Equal(t, a8m.ID, likes[0].UserID) + require.Equal(t, tweets[0].ID, likes[0].TweetID) + require.Equal(t, a8m.ID, likes[1].UserID) + require.Equal(t, tweets[1].ID, likes[1].TweetID) + ts := time.Unix(1653377090, 0) + like := client.TweetLike.Create().SetUser(a8m).SetLikedAt(ts).SetTweet(tweets[2]).SaveX(ctx) + require.Equal(t, a8m.ID, like.UserID) + require.Equal(t, tweets[2].ID, like.TweetID) + require.Equal(t, a8m.ID, like.QueryUser().OnlyIDX(ctx)) + require.Equal(t, tweets[2].ID, like.QueryTweet().OnlyIDX(ctx)) + require.Equal(t, 3, a8m.QueryLikes().CountX(ctx)) + require.Equal(t, []int{tweets[0].ID, tweets[1].ID, tweets[2].ID}, a8m.QueryLikes().QueryTweet().IDsX(ctx)) + for _, k := range []*ent.TweetLike{ + a8m.QueryLikes().Where(tweetlike.LikedAt(ts)).OnlyX(ctx), + client.TweetLike.Query().Where(tweetlike.LikedAt(ts)).OnlyX(ctx), + client.Tweet.Query().QueryLikes().Where(tweetlike.LikedAt(ts)).OnlyX(ctx), + client.Tweet.Query().QueryLikes().Where(tweetlike.LikedAt(ts), tweetlike.HasUserWith(user.Name(a8m.Name))).OnlyX(ctx), + client.User.Query().QueryLikedTweets().QueryLikes().Where(tweetlike.LikedAt(ts), tweetlike.HasUserWith(user.Name(a8m.Name))).OnlyX(ctx), + } { + require.Equal(t, like.UserID, k.UserID) + require.Equal(t, like.TweetID, k.TweetID) + require.Equal(t, like.LikedAt.Unix(), k.LikedAt.Unix()) + } + nat = nat.Update().AddLikedTweetIDs(like.TweetID).SaveX(ctx) + require.Equal(t, 2, nat.QueryLikes().CountX(ctx)) + require.Equal(t, 5, client.TweetLike.Query().CountX(ctx)) + require.Equal(t, 3, client.TweetLike.Query().Where(tweetlike.HasUserWith(user.Name(a8m.Name))).CountX(ctx)) + require.Equal(t, 2, client.TweetLike.Query().Where(tweetlike.HasUserWith(user.Name(nat.Name))).CountX(ctx)) + + var v []struct { + UserID int `sql:"user_id"` + Count int `sql:"count"` + } + client.TweetLike.Query().GroupBy(tweetlike.FieldUserID).Aggregate(ent.Count()).ScanX(ctx, &v) + require.Equal(t, a8m.ID, v[0].UserID) + require.Equal(t, 3, v[0].Count) + require.Equal(t, nat.ID, v[1].UserID) + require.Equal(t, 2, v[1].Count) +} + +func TestEdgeSchemaBidiWithID(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, migrate.WithGlobalUniqueID(true))) + + nat := client.User.Create().SetName("nati").SaveX(ctx) + a8m := client.User.Create().SetName("a8m").AddFriends(nat).SaveX(ctx) + for _, f1 := range []*ent.Friendship{ + a8m.QueryFriendships().OnlyX(ctx), + nat.QueryFriendships().QueryFriend().QueryFriendships().OnlyX(ctx), + client.Friendship.Query().Where(friendship.HasFriendWith(user.Name(nat.Name))).OnlyX(ctx), + } { + require.Equal(t, friendship.DefaultWeight, f1.Weight) + require.False(t, f1.CreatedAt.IsZero()) + require.Equal(t, a8m.ID, f1.UserID) + require.Equal(t, nat.ID, f1.FriendID) + } + require.Equal(t, 2, client.Friendship.Query().CountX(ctx), "bidirectional edges create 2 records in the join table") +} + +func TestEdgeSchemaBidiCompositeID(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, migrate.WithGlobalUniqueID(true))) + + u1 := client.User.Create().SetName("u1").SaveX(ctx) + u2 := client.User.Create().SetName("u2").AddRelatives(u1).SaveX(ctx) + u3 := client.User.Create().SetName("u3").AddRelatives(u2).SaveX(ctx) + + var v []struct { + UserID int `sql:"user_id"` + Count int `sql:"count"` + } + client.Relationship.Query().GroupBy(relationship.FieldUserID).Aggregate(ent.Count()).ScanX(ctx, &v) + require.EqualValues( + t, + []struct{ UserID, Count int }{{u1.ID, 1}, {u2.ID, 2}, {u3.ID, 1}}, + v, + ) + for _, r := range []int{ + u2.QueryRelationship().Where(relationship.RelativeID(u3.ID)).QueryRelative().OnlyIDX(ctx), + u1.QueryRelatives().QueryRelationship().Where(relationship.RelativeIDNEQ(u1.ID)).QueryRelative().OnlyIDX(ctx), + client.User.Query().Where(user.ID(u1.ID)).QueryRelatives().QueryRelationship().Where(relationship.RelativeIDNEQ(u1.ID)).QueryRelative().OnlyIDX(ctx), + } { + require.Equal(t, u3.ID, r) + } +} diff --git a/entc/integration/edgeschema/ent/client.go b/entc/integration/edgeschema/ent/client.go new file mode 100644 index 0000000000..2836269544 --- /dev/null +++ b/entc/integration/edgeschema/ent/client.go @@ -0,0 +1,1016 @@ +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "fmt" + "log" + + "entgo.io/ent/entc/integration/edgeschema/ent/migrate" + + "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/tweet" + "entgo.io/ent/entc/integration/edgeschema/ent/tweetlike" + "entgo.io/ent/entc/integration/edgeschema/ent/user" + "entgo.io/ent/entc/integration/edgeschema/ent/usergroup" + + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +// Client is the client that holds all ent builders. +type Client struct { + config + // Schema is the client for creating, migrating and dropping schema. + Schema *migrate.Schema + // Friendship is the client for interacting with the Friendship builders. + Friendship *FriendshipClient + // Group is the client for interacting with the Group builders. + Group *GroupClient + // Relationship is the client for interacting with the Relationship builders. + Relationship *RelationshipClient + // Tweet is the client for interacting with the Tweet builders. + Tweet *TweetClient + // TweetLike is the client for interacting with the TweetLike builders. + TweetLike *TweetLikeClient + // User is the client for interacting with the User builders. + User *UserClient + // UserGroup is the client for interacting with the UserGroup builders. + UserGroup *UserGroupClient +} + +// NewClient creates a new client configured with the given options. +func NewClient(opts ...Option) *Client { + cfg := config{log: log.Println, hooks: &hooks{}} + cfg.options(opts...) + client := &Client{config: cfg} + client.init() + return client +} + +func (c *Client) init() { + c.Schema = migrate.NewSchema(c.driver) + c.Friendship = NewFriendshipClient(c.config) + c.Group = NewGroupClient(c.config) + c.Relationship = NewRelationshipClient(c.config) + c.Tweet = NewTweetClient(c.config) + c.TweetLike = NewTweetLikeClient(c.config) + c.User = NewUserClient(c.config) + c.UserGroup = NewUserGroupClient(c.config) +} + +// Open opens a database/sql.DB specified by the driver name and +// the data source name, and returns a new client attached to it. +// Optional parameters can be added for configuring the client. +func Open(driverName, dataSourceName string, options ...Option) (*Client, error) { + switch driverName { + case dialect.MySQL, dialect.Postgres, dialect.SQLite: + drv, err := sql.Open(driverName, dataSourceName) + if err != nil { + return nil, err + } + return NewClient(append(options, Driver(drv))...), nil + default: + return nil, fmt.Errorf("unsupported driver: %q", driverName) + } +} + +// Tx returns a new transactional client. The provided context +// is used until the transaction is committed or rolled back. +func (c *Client) Tx(ctx context.Context) (*Tx, error) { + if _, ok := c.driver.(*txDriver); ok { + return nil, fmt.Errorf("ent: cannot start a transaction within a transaction") + } + tx, err := newTx(ctx, c.driver) + if err != nil { + return nil, fmt.Errorf("ent: starting a transaction: %w", err) + } + cfg := c.config + cfg.driver = tx + return &Tx{ + ctx: ctx, + config: cfg, + Friendship: NewFriendshipClient(cfg), + Group: NewGroupClient(cfg), + Relationship: NewRelationshipClient(cfg), + Tweet: NewTweetClient(cfg), + TweetLike: NewTweetLikeClient(cfg), + User: NewUserClient(cfg), + UserGroup: NewUserGroupClient(cfg), + }, nil +} + +// BeginTx returns a transactional client with specified options. +func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) { + if _, ok := c.driver.(*txDriver); ok { + return nil, fmt.Errorf("ent: cannot start a transaction within a transaction") + } + tx, err := c.driver.(interface { + BeginTx(context.Context, *sql.TxOptions) (dialect.Tx, error) + }).BeginTx(ctx, opts) + if err != nil { + return nil, fmt.Errorf("ent: starting a transaction: %w", err) + } + cfg := c.config + cfg.driver = &txDriver{tx: tx, drv: c.driver} + return &Tx{ + ctx: ctx, + config: cfg, + Friendship: NewFriendshipClient(cfg), + Group: NewGroupClient(cfg), + Relationship: NewRelationshipClient(cfg), + Tweet: NewTweetClient(cfg), + TweetLike: NewTweetLikeClient(cfg), + User: NewUserClient(cfg), + UserGroup: NewUserGroupClient(cfg), + }, nil +} + +// Debug returns a new debug-client. It's used to get verbose logging on specific operations. +// +// client.Debug(). +// Friendship. +// Query(). +// Count(ctx) +// +func (c *Client) Debug() *Client { + if c.debug { + return c + } + cfg := c.config + cfg.driver = dialect.Debug(c.driver, c.log) + client := &Client{config: cfg} + client.init() + return client +} + +// Close closes the database connection and prevents new queries from starting. +func (c *Client) Close() error { + return c.driver.Close() +} + +// Use adds the mutation hooks to all the entity clients. +// In order to add hooks to a specific client, call: `client.Node.Use(...)`. +func (c *Client) Use(hooks ...Hook) { + c.Friendship.Use(hooks...) + c.Group.Use(hooks...) + c.Relationship.Use(hooks...) + c.Tweet.Use(hooks...) + c.TweetLike.Use(hooks...) + c.User.Use(hooks...) + c.UserGroup.Use(hooks...) +} + +// FriendshipClient is a client for the Friendship schema. +type FriendshipClient struct { + config +} + +// NewFriendshipClient returns a client for the Friendship from the given config. +func NewFriendshipClient(c config) *FriendshipClient { + return &FriendshipClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `friendship.Hooks(f(g(h())))`. +func (c *FriendshipClient) Use(hooks ...Hook) { + c.hooks.Friendship = append(c.hooks.Friendship, hooks...) +} + +// Create returns a builder for creating a Friendship entity. +func (c *FriendshipClient) Create() *FriendshipCreate { + mutation := newFriendshipMutation(c.config, OpCreate) + return &FriendshipCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of Friendship entities. +func (c *FriendshipClient) CreateBulk(builders ...*FriendshipCreate) *FriendshipCreateBulk { + return &FriendshipCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for Friendship. +func (c *FriendshipClient) Update() *FriendshipUpdate { + mutation := newFriendshipMutation(c.config, OpUpdate) + return &FriendshipUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *FriendshipClient) UpdateOne(f *Friendship) *FriendshipUpdateOne { + mutation := newFriendshipMutation(c.config, OpUpdateOne, withFriendship(f)) + return &FriendshipUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *FriendshipClient) UpdateOneID(id int) *FriendshipUpdateOne { + mutation := newFriendshipMutation(c.config, OpUpdateOne, withFriendshipID(id)) + return &FriendshipUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Friendship. +func (c *FriendshipClient) Delete() *FriendshipDelete { + mutation := newFriendshipMutation(c.config, OpDelete) + return &FriendshipDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *FriendshipClient) DeleteOne(f *Friendship) *FriendshipDeleteOne { + return c.DeleteOneID(f.ID) +} + +// DeleteOne returns a builder for deleting the given entity by its id. +func (c *FriendshipClient) DeleteOneID(id int) *FriendshipDeleteOne { + builder := c.Delete().Where(friendship.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &FriendshipDeleteOne{builder} +} + +// Query returns a query builder for Friendship. +func (c *FriendshipClient) Query() *FriendshipQuery { + return &FriendshipQuery{ + config: c.config, + } +} + +// Get returns a Friendship entity by its id. +func (c *FriendshipClient) Get(ctx context.Context, id int) (*Friendship, error) { + return c.Query().Where(friendship.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *FriendshipClient) GetX(ctx context.Context, id int) *Friendship { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryUser queries the user edge of a Friendship. +func (c *FriendshipClient) QueryUser(f *Friendship) *UserQuery { + query := &UserQuery{config: c.config} + query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + id := f.ID + step := sqlgraph.NewStep( + sqlgraph.From(friendship.Table, friendship.FieldID, id), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, friendship.UserTable, friendship.UserColumn), + ) + fromV = sqlgraph.Neighbors(f.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryFriend queries the friend edge of a Friendship. +func (c *FriendshipClient) QueryFriend(f *Friendship) *UserQuery { + query := &UserQuery{config: c.config} + query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + id := f.ID + step := sqlgraph.NewStep( + sqlgraph.From(friendship.Table, friendship.FieldID, id), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, friendship.FriendTable, friendship.FriendColumn), + ) + fromV = sqlgraph.Neighbors(f.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *FriendshipClient) Hooks() []Hook { + return c.hooks.Friendship +} + +// GroupClient is a client for the Group schema. +type GroupClient struct { + config +} + +// NewGroupClient returns a client for the Group from the given config. +func NewGroupClient(c config) *GroupClient { + return &GroupClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `group.Hooks(f(g(h())))`. +func (c *GroupClient) Use(hooks ...Hook) { + c.hooks.Group = append(c.hooks.Group, hooks...) +} + +// Create returns a builder for creating a Group entity. +func (c *GroupClient) Create() *GroupCreate { + mutation := newGroupMutation(c.config, OpCreate) + return &GroupCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of Group entities. +func (c *GroupClient) CreateBulk(builders ...*GroupCreate) *GroupCreateBulk { + return &GroupCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for Group. +func (c *GroupClient) Update() *GroupUpdate { + mutation := newGroupMutation(c.config, OpUpdate) + return &GroupUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *GroupClient) UpdateOne(gr *Group) *GroupUpdateOne { + mutation := newGroupMutation(c.config, OpUpdateOne, withGroup(gr)) + return &GroupUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *GroupClient) UpdateOneID(id int) *GroupUpdateOne { + mutation := newGroupMutation(c.config, OpUpdateOne, withGroupID(id)) + return &GroupUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Group. +func (c *GroupClient) Delete() *GroupDelete { + mutation := newGroupMutation(c.config, OpDelete) + return &GroupDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *GroupClient) DeleteOne(gr *Group) *GroupDeleteOne { + return c.DeleteOneID(gr.ID) +} + +// DeleteOne returns a builder for deleting the given entity by its id. +func (c *GroupClient) DeleteOneID(id int) *GroupDeleteOne { + builder := c.Delete().Where(group.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &GroupDeleteOne{builder} +} + +// Query returns a query builder for Group. +func (c *GroupClient) Query() *GroupQuery { + return &GroupQuery{ + config: c.config, + } +} + +// Get returns a Group entity by its id. +func (c *GroupClient) Get(ctx context.Context, id int) (*Group, error) { + return c.Query().Where(group.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *GroupClient) GetX(ctx context.Context, id int) *Group { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryUsers queries the users edge of a Group. +func (c *GroupClient) QueryUsers(gr *Group) *UserQuery { + query := &UserQuery{config: c.config} + query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + id := gr.ID + step := sqlgraph.NewStep( + sqlgraph.From(group.Table, group.FieldID, id), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, group.UsersTable, group.UsersPrimaryKey...), + ) + fromV = sqlgraph.Neighbors(gr.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryJoinedUsers queries the joined_users edge of a Group. +func (c *GroupClient) QueryJoinedUsers(gr *Group) *UserGroupQuery { + query := &UserGroupQuery{config: c.config} + query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + id := gr.ID + step := sqlgraph.NewStep( + sqlgraph.From(group.Table, group.FieldID, id), + sqlgraph.To(usergroup.Table, usergroup.FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, group.JoinedUsersTable, group.JoinedUsersColumn), + ) + fromV = sqlgraph.Neighbors(gr.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *GroupClient) Hooks() []Hook { + return c.hooks.Group +} + +// RelationshipClient is a client for the Relationship schema. +type RelationshipClient struct { + config +} + +// NewRelationshipClient returns a client for the Relationship from the given config. +func NewRelationshipClient(c config) *RelationshipClient { + return &RelationshipClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `relationship.Hooks(f(g(h())))`. +func (c *RelationshipClient) Use(hooks ...Hook) { + c.hooks.Relationship = append(c.hooks.Relationship, hooks...) +} + +// Create returns a builder for creating a Relationship entity. +func (c *RelationshipClient) Create() *RelationshipCreate { + mutation := newRelationshipMutation(c.config, OpCreate) + return &RelationshipCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of Relationship entities. +func (c *RelationshipClient) CreateBulk(builders ...*RelationshipCreate) *RelationshipCreateBulk { + return &RelationshipCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for Relationship. +func (c *RelationshipClient) Update() *RelationshipUpdate { + mutation := newRelationshipMutation(c.config, OpUpdate) + return &RelationshipUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *RelationshipClient) UpdateOne(r *Relationship) *RelationshipUpdateOne { + mutation := newRelationshipMutation(c.config, OpUpdateOne) + mutation.Where(relationship.UserID(r.UserID), relationship.RelativeID(r.RelativeID)) + return &RelationshipUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Relationship. +func (c *RelationshipClient) Delete() *RelationshipDelete { + mutation := newRelationshipMutation(c.config, OpDelete) + return &RelationshipDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Query returns a query builder for Relationship. +func (c *RelationshipClient) Query() *RelationshipQuery { + return &RelationshipQuery{ + config: c.config, + } +} + +// QueryUser queries the user edge of a Relationship. +func (c *RelationshipClient) QueryUser(r *Relationship) *UserQuery { + return c.Query(). + Where(relationship.UserID(r.UserID), relationship.RelativeID(r.RelativeID)). + QueryUser() +} + +// QueryRelative queries the relative edge of a Relationship. +func (c *RelationshipClient) QueryRelative(r *Relationship) *UserQuery { + return c.Query(). + Where(relationship.UserID(r.UserID), relationship.RelativeID(r.RelativeID)). + QueryRelative() +} + +// Hooks returns the client hooks. +func (c *RelationshipClient) Hooks() []Hook { + return c.hooks.Relationship +} + +// TweetClient is a client for the Tweet schema. +type TweetClient struct { + config +} + +// NewTweetClient returns a client for the Tweet from the given config. +func NewTweetClient(c config) *TweetClient { + return &TweetClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `tweet.Hooks(f(g(h())))`. +func (c *TweetClient) Use(hooks ...Hook) { + c.hooks.Tweet = append(c.hooks.Tweet, hooks...) +} + +// Create returns a builder for creating a Tweet entity. +func (c *TweetClient) Create() *TweetCreate { + mutation := newTweetMutation(c.config, OpCreate) + return &TweetCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of Tweet entities. +func (c *TweetClient) CreateBulk(builders ...*TweetCreate) *TweetCreateBulk { + return &TweetCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for Tweet. +func (c *TweetClient) Update() *TweetUpdate { + mutation := newTweetMutation(c.config, OpUpdate) + return &TweetUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *TweetClient) UpdateOne(t *Tweet) *TweetUpdateOne { + mutation := newTweetMutation(c.config, OpUpdateOne, withTweet(t)) + return &TweetUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *TweetClient) UpdateOneID(id int) *TweetUpdateOne { + mutation := newTweetMutation(c.config, OpUpdateOne, withTweetID(id)) + return &TweetUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Tweet. +func (c *TweetClient) Delete() *TweetDelete { + mutation := newTweetMutation(c.config, OpDelete) + return &TweetDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *TweetClient) DeleteOne(t *Tweet) *TweetDeleteOne { + return c.DeleteOneID(t.ID) +} + +// DeleteOne returns a builder for deleting the given entity by its id. +func (c *TweetClient) DeleteOneID(id int) *TweetDeleteOne { + builder := c.Delete().Where(tweet.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &TweetDeleteOne{builder} +} + +// Query returns a query builder for Tweet. +func (c *TweetClient) Query() *TweetQuery { + return &TweetQuery{ + config: c.config, + } +} + +// Get returns a Tweet entity by its id. +func (c *TweetClient) Get(ctx context.Context, id int) (*Tweet, error) { + return c.Query().Where(tweet.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *TweetClient) GetX(ctx context.Context, id int) *Tweet { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryLikedUsers queries the liked_users edge of a Tweet. +func (c *TweetClient) QueryLikedUsers(t *Tweet) *UserQuery { + query := &UserQuery{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(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, tweet.LikedUsersTable, tweet.LikedUsersPrimaryKey...), + ) + 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} + 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(tweetlike.Table, tweetlike.TweetColumn), + sqlgraph.Edge(sqlgraph.O2M, true, tweet.LikesTable, tweet.LikesColumn), + ) + 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 +} + +// TweetLikeClient is a client for the TweetLike schema. +type TweetLikeClient struct { + config +} + +// NewTweetLikeClient returns a client for the TweetLike from the given config. +func NewTweetLikeClient(c config) *TweetLikeClient { + return &TweetLikeClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `tweetlike.Hooks(f(g(h())))`. +func (c *TweetLikeClient) Use(hooks ...Hook) { + c.hooks.TweetLike = append(c.hooks.TweetLike, hooks...) +} + +// Create returns a builder for creating a TweetLike entity. +func (c *TweetLikeClient) Create() *TweetLikeCreate { + mutation := newTweetLikeMutation(c.config, OpCreate) + return &TweetLikeCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of TweetLike entities. +func (c *TweetLikeClient) CreateBulk(builders ...*TweetLikeCreate) *TweetLikeCreateBulk { + return &TweetLikeCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for TweetLike. +func (c *TweetLikeClient) Update() *TweetLikeUpdate { + mutation := newTweetLikeMutation(c.config, OpUpdate) + return &TweetLikeUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *TweetLikeClient) UpdateOne(tl *TweetLike) *TweetLikeUpdateOne { + mutation := newTweetLikeMutation(c.config, OpUpdateOne) + mutation.Where(tweetlike.UserID(tl.UserID), tweetlike.TweetID(tl.TweetID)) + return &TweetLikeUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for TweetLike. +func (c *TweetLikeClient) Delete() *TweetLikeDelete { + mutation := newTweetLikeMutation(c.config, OpDelete) + return &TweetLikeDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Query returns a query builder for TweetLike. +func (c *TweetLikeClient) Query() *TweetLikeQuery { + return &TweetLikeQuery{ + config: c.config, + } +} + +// QueryUser queries the user edge of a TweetLike. +func (c *TweetLikeClient) QueryUser(tl *TweetLike) *UserQuery { + return c.Query(). + Where(tweetlike.UserID(tl.UserID), tweetlike.TweetID(tl.TweetID)). + QueryUser() +} + +// QueryTweet queries the tweet edge of a TweetLike. +func (c *TweetLikeClient) QueryTweet(tl *TweetLike) *TweetQuery { + return c.Query(). + Where(tweetlike.UserID(tl.UserID), tweetlike.TweetID(tl.TweetID)). + QueryTweet() +} + +// Hooks returns the client hooks. +func (c *TweetLikeClient) Hooks() []Hook { + return c.hooks.TweetLike +} + +// UserClient is a client for the User schema. +type UserClient struct { + config +} + +// NewUserClient returns a client for the User from the given config. +func NewUserClient(c config) *UserClient { + return &UserClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `user.Hooks(f(g(h())))`. +func (c *UserClient) Use(hooks ...Hook) { + c.hooks.User = append(c.hooks.User, hooks...) +} + +// Create returns a builder for creating a User entity. +func (c *UserClient) Create() *UserCreate { + mutation := newUserMutation(c.config, OpCreate) + return &UserCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of User entities. +func (c *UserClient) CreateBulk(builders ...*UserCreate) *UserCreateBulk { + return &UserCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for User. +func (c *UserClient) Update() *UserUpdate { + mutation := newUserMutation(c.config, OpUpdate) + return &UserUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *UserClient) UpdateOne(u *User) *UserUpdateOne { + mutation := newUserMutation(c.config, OpUpdateOne, withUser(u)) + return &UserUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *UserClient) UpdateOneID(id int) *UserUpdateOne { + mutation := newUserMutation(c.config, OpUpdateOne, withUserID(id)) + return &UserUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for User. +func (c *UserClient) Delete() *UserDelete { + mutation := newUserMutation(c.config, OpDelete) + return &UserDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *UserClient) DeleteOne(u *User) *UserDeleteOne { + return c.DeleteOneID(u.ID) +} + +// DeleteOne returns a builder for deleting the given entity by its id. +func (c *UserClient) DeleteOneID(id int) *UserDeleteOne { + builder := c.Delete().Where(user.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &UserDeleteOne{builder} +} + +// Query returns a query builder for User. +func (c *UserClient) Query() *UserQuery { + return &UserQuery{ + config: c.config, + } +} + +// Get returns a User entity by its id. +func (c *UserClient) Get(ctx context.Context, id int) (*User, error) { + return c.Query().Where(user.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *UserClient) GetX(ctx context.Context, id int) *User { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryLikedTweets queries the liked_tweets edge of a User. +func (c *UserClient) QueryLikedTweets(u *User) *TweetQuery { + query := &TweetQuery{config: c.config} + query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + id := u.ID + step := sqlgraph.NewStep( + sqlgraph.From(user.Table, user.FieldID, id), + sqlgraph.To(tweet.Table, tweet.FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, user.LikedTweetsTable, user.LikedTweetsPrimaryKey...), + ) + fromV = sqlgraph.Neighbors(u.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryGroups queries the groups edge of a User. +func (c *UserClient) QueryGroups(u *User) *GroupQuery { + query := &GroupQuery{config: c.config} + query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + id := u.ID + step := sqlgraph.NewStep( + sqlgraph.From(user.Table, user.FieldID, id), + sqlgraph.To(group.Table, group.FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, user.GroupsTable, user.GroupsPrimaryKey...), + ) + fromV = sqlgraph.Neighbors(u.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryFriends queries the friends edge of a User. +func (c *UserClient) QueryFriends(u *User) *UserQuery { + query := &UserQuery{config: c.config} + query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + id := u.ID + step := sqlgraph.NewStep( + sqlgraph.From(user.Table, user.FieldID, id), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, user.FriendsTable, user.FriendsPrimaryKey...), + ) + fromV = sqlgraph.Neighbors(u.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryRelatives queries the relatives edge of a User. +func (c *UserClient) QueryRelatives(u *User) *UserQuery { + query := &UserQuery{config: c.config} + query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + id := u.ID + step := sqlgraph.NewStep( + sqlgraph.From(user.Table, user.FieldID, id), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, user.RelativesTable, user.RelativesPrimaryKey...), + ) + fromV = sqlgraph.Neighbors(u.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryLikes queries the likes edge of a User. +func (c *UserClient) QueryLikes(u *User) *TweetLikeQuery { + query := &TweetLikeQuery{config: c.config} + query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + id := u.ID + step := sqlgraph.NewStep( + sqlgraph.From(user.Table, user.FieldID, id), + sqlgraph.To(tweetlike.Table, tweetlike.UserColumn), + sqlgraph.Edge(sqlgraph.O2M, true, user.LikesTable, user.LikesColumn), + ) + fromV = sqlgraph.Neighbors(u.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryJoinedGroups queries the joined_groups edge of a User. +func (c *UserClient) QueryJoinedGroups(u *User) *UserGroupQuery { + query := &UserGroupQuery{config: c.config} + query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + id := u.ID + step := sqlgraph.NewStep( + sqlgraph.From(user.Table, user.FieldID, id), + sqlgraph.To(usergroup.Table, usergroup.FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, user.JoinedGroupsTable, user.JoinedGroupsColumn), + ) + fromV = sqlgraph.Neighbors(u.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryFriendships queries the friendships edge of a User. +func (c *UserClient) QueryFriendships(u *User) *FriendshipQuery { + query := &FriendshipQuery{config: c.config} + query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + id := u.ID + step := sqlgraph.NewStep( + sqlgraph.From(user.Table, user.FieldID, id), + sqlgraph.To(friendship.Table, friendship.FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, user.FriendshipsTable, user.FriendshipsColumn), + ) + fromV = sqlgraph.Neighbors(u.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryRelationship queries the relationship edge of a User. +func (c *UserClient) QueryRelationship(u *User) *RelationshipQuery { + query := &RelationshipQuery{config: c.config} + query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + id := u.ID + step := sqlgraph.NewStep( + sqlgraph.From(user.Table, user.FieldID, id), + sqlgraph.To(relationship.Table, relationship.UserColumn), + sqlgraph.Edge(sqlgraph.O2M, true, user.RelationshipTable, user.RelationshipColumn), + ) + fromV = sqlgraph.Neighbors(u.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *UserClient) Hooks() []Hook { + return c.hooks.User +} + +// UserGroupClient is a client for the UserGroup schema. +type UserGroupClient struct { + config +} + +// NewUserGroupClient returns a client for the UserGroup from the given config. +func NewUserGroupClient(c config) *UserGroupClient { + return &UserGroupClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `usergroup.Hooks(f(g(h())))`. +func (c *UserGroupClient) Use(hooks ...Hook) { + c.hooks.UserGroup = append(c.hooks.UserGroup, hooks...) +} + +// Create returns a builder for creating a UserGroup entity. +func (c *UserGroupClient) Create() *UserGroupCreate { + mutation := newUserGroupMutation(c.config, OpCreate) + return &UserGroupCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of UserGroup entities. +func (c *UserGroupClient) CreateBulk(builders ...*UserGroupCreate) *UserGroupCreateBulk { + return &UserGroupCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for UserGroup. +func (c *UserGroupClient) Update() *UserGroupUpdate { + mutation := newUserGroupMutation(c.config, OpUpdate) + return &UserGroupUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *UserGroupClient) UpdateOne(ug *UserGroup) *UserGroupUpdateOne { + mutation := newUserGroupMutation(c.config, OpUpdateOne, withUserGroup(ug)) + return &UserGroupUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *UserGroupClient) UpdateOneID(id int) *UserGroupUpdateOne { + mutation := newUserGroupMutation(c.config, OpUpdateOne, withUserGroupID(id)) + return &UserGroupUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for UserGroup. +func (c *UserGroupClient) Delete() *UserGroupDelete { + mutation := newUserGroupMutation(c.config, OpDelete) + return &UserGroupDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *UserGroupClient) DeleteOne(ug *UserGroup) *UserGroupDeleteOne { + return c.DeleteOneID(ug.ID) +} + +// DeleteOne returns a builder for deleting the given entity by its id. +func (c *UserGroupClient) DeleteOneID(id int) *UserGroupDeleteOne { + builder := c.Delete().Where(usergroup.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &UserGroupDeleteOne{builder} +} + +// Query returns a query builder for UserGroup. +func (c *UserGroupClient) Query() *UserGroupQuery { + return &UserGroupQuery{ + config: c.config, + } +} + +// Get returns a UserGroup entity by its id. +func (c *UserGroupClient) Get(ctx context.Context, id int) (*UserGroup, error) { + return c.Query().Where(usergroup.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *UserGroupClient) GetX(ctx context.Context, id int) *UserGroup { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryUser queries the user edge of a UserGroup. +func (c *UserGroupClient) QueryUser(ug *UserGroup) *UserQuery { + query := &UserQuery{config: c.config} + query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + id := ug.ID + step := sqlgraph.NewStep( + sqlgraph.From(usergroup.Table, usergroup.FieldID, id), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, usergroup.UserTable, usergroup.UserColumn), + ) + fromV = sqlgraph.Neighbors(ug.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryGroup queries the group edge of a UserGroup. +func (c *UserGroupClient) QueryGroup(ug *UserGroup) *GroupQuery { + query := &GroupQuery{config: c.config} + query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + id := ug.ID + step := sqlgraph.NewStep( + sqlgraph.From(usergroup.Table, usergroup.FieldID, id), + sqlgraph.To(group.Table, group.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, usergroup.GroupTable, usergroup.GroupColumn), + ) + fromV = sqlgraph.Neighbors(ug.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *UserGroupClient) Hooks() []Hook { + return c.hooks.UserGroup +} diff --git a/entc/integration/edgeschema/ent/config.go b/entc/integration/edgeschema/ent/config.go new file mode 100644 index 0000000000..b999df3e46 --- /dev/null +++ b/entc/integration/edgeschema/ent/config.go @@ -0,0 +1,65 @@ +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "entgo.io/ent" + "entgo.io/ent/dialect" +) + +// Option function to configure the client. +type Option func(*config) + +// Config is the configuration for the client and its builder. +type config struct { + // driver used for executing database requests. + driver dialect.Driver + // debug enable a debug logging. + debug bool + // log used for logging on debug mode. + log func(...interface{}) + // hooks to execute on mutations. + hooks *hooks +} + +// hooks per client, for fast access. +type hooks struct { + Friendship []ent.Hook + Group []ent.Hook + Relationship []ent.Hook + Tweet []ent.Hook + TweetLike []ent.Hook + User []ent.Hook + UserGroup []ent.Hook +} + +// Options applies the options on the config object. +func (c *config) options(opts ...Option) { + for _, opt := range opts { + opt(c) + } + if c.debug { + c.driver = dialect.Debug(c.driver, c.log) + } +} + +// Debug enables debug logging on the ent.Driver. +func Debug() Option { + return func(c *config) { + c.debug = true + } +} + +// Log sets the logging function for debug mode. +func Log(fn func(...interface{})) Option { + return func(c *config) { + c.log = fn + } +} + +// Driver configures the client driver. +func Driver(driver dialect.Driver) Option { + return func(c *config) { + c.driver = driver + } +} diff --git a/entc/integration/edgeschema/ent/context.go b/entc/integration/edgeschema/ent/context.go new file mode 100644 index 0000000000..08407261be --- /dev/null +++ b/entc/integration/edgeschema/ent/context.go @@ -0,0 +1,33 @@ +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" +) + +type clientCtxKey struct{} + +// FromContext returns a Client stored inside a context, or nil if there isn't one. +func FromContext(ctx context.Context) *Client { + c, _ := ctx.Value(clientCtxKey{}).(*Client) + return c +} + +// NewContext returns a new context with the given Client attached. +func NewContext(parent context.Context, c *Client) context.Context { + return context.WithValue(parent, clientCtxKey{}, c) +} + +type txCtxKey struct{} + +// TxFromContext returns a Tx stored inside a context, or nil if there isn't one. +func TxFromContext(ctx context.Context) *Tx { + tx, _ := ctx.Value(txCtxKey{}).(*Tx) + return tx +} + +// NewTxContext returns a new context with the given Tx attached. +func NewTxContext(parent context.Context, tx *Tx) context.Context { + return context.WithValue(parent, txCtxKey{}, tx) +} diff --git a/entc/integration/edgeschema/ent/ent.go b/entc/integration/edgeschema/ent/ent.go new file mode 100644 index 0000000000..5e094cb980 --- /dev/null +++ b/entc/integration/edgeschema/ent/ent.go @@ -0,0 +1,478 @@ +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "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/tweet" + "entgo.io/ent/entc/integration/edgeschema/ent/tweetlike" + "entgo.io/ent/entc/integration/edgeschema/ent/user" + "entgo.io/ent/entc/integration/edgeschema/ent/usergroup" +) + +// ent aliases to avoid import conflicts in user's code. +type ( + Op = ent.Op + Hook = ent.Hook + Value = ent.Value + Query = ent.Query + Policy = ent.Policy + Mutator = ent.Mutator + Mutation = ent.Mutation + MutateFunc = ent.MutateFunc +) + +// OrderFunc applies an ordering on the sql selector. +type OrderFunc func(*sql.Selector) + +// columnChecker returns a function indicates if the column exists in the given column. +func columnChecker(table string) func(string) error { + checks := map[string]func(string) bool{ + friendship.Table: friendship.ValidColumn, + group.Table: group.ValidColumn, + relationship.Table: relationship.ValidColumn, + tweet.Table: tweet.ValidColumn, + tweetlike.Table: tweetlike.ValidColumn, + user.Table: user.ValidColumn, + usergroup.Table: usergroup.ValidColumn, + } + check, ok := checks[table] + if !ok { + return func(string) error { + return fmt.Errorf("unknown table %q", table) + } + } + return func(column string) error { + if !check(column) { + return fmt.Errorf("unknown column %q for table %q", column, table) + } + return nil + } +} + +// Asc applies the given fields in ASC order. +func Asc(fields ...string) OrderFunc { + return func(s *sql.Selector) { + check := columnChecker(s.TableName()) + for _, f := range fields { + if err := check(f); err != nil { + s.AddError(&ValidationError{Name: f, err: fmt.Errorf("ent: %w", err)}) + } + s.OrderBy(sql.Asc(s.C(f))) + } + } +} + +// Desc applies the given fields in DESC order. +func Desc(fields ...string) OrderFunc { + return func(s *sql.Selector) { + check := columnChecker(s.TableName()) + for _, f := range fields { + if err := check(f); err != nil { + s.AddError(&ValidationError{Name: f, err: fmt.Errorf("ent: %w", err)}) + } + s.OrderBy(sql.Desc(s.C(f))) + } + } +} + +// AggregateFunc applies an aggregation step on the group-by traversal/selector. +type AggregateFunc func(*sql.Selector) string + +// As is a pseudo aggregation function for renaming another other functions with custom names. For example: +// +// GroupBy(field1, field2). +// Aggregate(ent.As(ent.Sum(field1), "sum_field1"), (ent.As(ent.Sum(field2), "sum_field2")). +// Scan(ctx, &v) +// +func As(fn AggregateFunc, end string) AggregateFunc { + return func(s *sql.Selector) string { + return sql.As(fn(s), end) + } +} + +// Count applies the "count" aggregation function on each group. +func Count() AggregateFunc { + return func(s *sql.Selector) string { + return sql.Count("*") + } +} + +// Max applies the "max" aggregation function on the given field of each group. +func Max(field string) AggregateFunc { + return func(s *sql.Selector) string { + check := columnChecker(s.TableName()) + if err := check(field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)}) + return "" + } + return sql.Max(s.C(field)) + } +} + +// Mean applies the "mean" aggregation function on the given field of each group. +func Mean(field string) AggregateFunc { + return func(s *sql.Selector) string { + check := columnChecker(s.TableName()) + if err := check(field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)}) + return "" + } + return sql.Avg(s.C(field)) + } +} + +// Min applies the "min" aggregation function on the given field of each group. +func Min(field string) AggregateFunc { + return func(s *sql.Selector) string { + check := columnChecker(s.TableName()) + if err := check(field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)}) + return "" + } + return sql.Min(s.C(field)) + } +} + +// Sum applies the "sum" aggregation function on the given field of each group. +func Sum(field string) AggregateFunc { + return func(s *sql.Selector) string { + check := columnChecker(s.TableName()) + if err := check(field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)}) + return "" + } + return sql.Sum(s.C(field)) + } +} + +// ValidationError returns when validating a field or edge fails. +type ValidationError struct { + Name string // Field or edge name. + err error +} + +// Error implements the error interface. +func (e *ValidationError) Error() string { + return e.err.Error() +} + +// Unwrap implements the errors.Wrapper interface. +func (e *ValidationError) Unwrap() error { + return e.err +} + +// IsValidationError returns a boolean indicating whether the error is a validation error. +func IsValidationError(err error) bool { + if err == nil { + return false + } + var e *ValidationError + return errors.As(err, &e) +} + +// NotFoundError returns when trying to fetch a specific entity and it was not found in the database. +type NotFoundError struct { + label string +} + +// Error implements the error interface. +func (e *NotFoundError) Error() string { + return "ent: " + e.label + " not found" +} + +// IsNotFound returns a boolean indicating whether the error is a not found error. +func IsNotFound(err error) bool { + if err == nil { + return false + } + var e *NotFoundError + return errors.As(err, &e) +} + +// MaskNotFound masks not found error. +func MaskNotFound(err error) error { + if IsNotFound(err) { + return nil + } + return err +} + +// NotSingularError returns when trying to fetch a singular entity and more then one was found in the database. +type NotSingularError struct { + label string +} + +// Error implements the error interface. +func (e *NotSingularError) Error() string { + return "ent: " + e.label + " not singular" +} + +// IsNotSingular returns a boolean indicating whether the error is a not singular error. +func IsNotSingular(err error) bool { + if err == nil { + return false + } + var e *NotSingularError + return errors.As(err, &e) +} + +// NotLoadedError returns when trying to get a node that was not loaded by the query. +type NotLoadedError struct { + edge string +} + +// Error implements the error interface. +func (e *NotLoadedError) Error() string { + return "ent: " + e.edge + " edge was not loaded" +} + +// IsNotLoaded returns a boolean indicating whether the error is a not loaded error. +func IsNotLoaded(err error) bool { + if err == nil { + return false + } + var e *NotLoadedError + return errors.As(err, &e) +} + +// ConstraintError returns when trying to create/update one or more entities and +// one or more of their constraints failed. For example, violation of edge or +// field uniqueness. +type ConstraintError struct { + msg string + wrap error +} + +// Error implements the error interface. +func (e ConstraintError) Error() string { + return "ent: constraint failed: " + e.msg +} + +// Unwrap implements the errors.Wrapper interface. +func (e *ConstraintError) Unwrap() error { + return e.wrap +} + +// IsConstraintError returns a boolean indicating whether the error is a constraint failure. +func IsConstraintError(err error) bool { + if err == nil { + return false + } + var e *ConstraintError + return errors.As(err, &e) +} + +// selector embedded by the different Select/GroupBy builders. +type selector struct { + label string + flds *[]string + scan func(context.Context, interface{}) error +} + +// ScanX is like Scan, but panics if an error occurs. +func (s *selector) ScanX(ctx context.Context, v interface{}) { + if err := s.scan(ctx, v); err != nil { + panic(err) + } +} + +// Strings returns list of strings from a selector. It is only allowed when selecting one field. +func (s *selector) Strings(ctx context.Context) ([]string, error) { + if len(*s.flds) > 1 { + return nil, errors.New("ent: Strings is not achievable when selecting more than 1 field") + } + var v []string + if err := s.scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (s *selector) StringsX(ctx context.Context) []string { + v, err := s.Strings(ctx) + if err != nil { + panic(err) + } + return v +} + +// String returns a single string from a selector. It is only allowed when selecting one field. +func (s *selector) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = s.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{s.label} + default: + err = fmt.Errorf("ent: Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (s *selector) StringX(ctx context.Context) string { + v, err := s.String(ctx) + if err != nil { + panic(err) + } + return v +} + +// Ints returns list of ints from a selector. It is only allowed when selecting one field. +func (s *selector) Ints(ctx context.Context) ([]int, error) { + if len(*s.flds) > 1 { + return nil, errors.New("ent: Ints is not achievable when selecting more than 1 field") + } + var v []int + if err := s.scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (s *selector) IntsX(ctx context.Context) []int { + v, err := s.Ints(ctx) + if err != nil { + panic(err) + } + return v +} + +// Int returns a single int from a selector. It is only allowed when selecting one field. +func (s *selector) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = s.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{s.label} + default: + err = fmt.Errorf("ent: Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (s *selector) IntX(ctx context.Context) int { + v, err := s.Int(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64s returns list of float64s from a selector. It is only allowed when selecting one field. +func (s *selector) Float64s(ctx context.Context) ([]float64, error) { + if len(*s.flds) > 1 { + return nil, errors.New("ent: Float64s is not achievable when selecting more than 1 field") + } + var v []float64 + if err := s.scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// Float64sX is like Float64s, but panics if an error occurs. +func (s *selector) Float64sX(ctx context.Context) []float64 { + v, err := s.Float64s(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64 returns a single float64 from a selector. It is only allowed when selecting one field. +func (s *selector) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = s.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{s.label} + default: + err = fmt.Errorf("ent: Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (s *selector) Float64X(ctx context.Context) float64 { + v, err := s.Float64(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bools returns list of bools from a selector. It is only allowed when selecting one field. +func (s *selector) Bools(ctx context.Context) ([]bool, error) { + if len(*s.flds) > 1 { + return nil, errors.New("ent: Bools is not achievable when selecting more than 1 field") + } + var v []bool + if err := s.scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (s *selector) BoolsX(ctx context.Context) []bool { + v, err := s.Bools(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bool returns a single bool from a selector. It is only allowed when selecting one field. +func (s *selector) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = s.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{s.label} + default: + err = fmt.Errorf("ent: Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (s *selector) BoolX(ctx context.Context) bool { + v, err := s.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +// queryHook describes an internal hook for the different sqlAll methods. +type queryHook func(context.Context, *sqlgraph.QuerySpec) diff --git a/entc/integration/edgeschema/ent/enttest/enttest.go b/entc/integration/edgeschema/ent/enttest/enttest.go new file mode 100644 index 0000000000..0f52ee92b3 --- /dev/null +++ b/entc/integration/edgeschema/ent/enttest/enttest.go @@ -0,0 +1,78 @@ +// Code generated by entc, DO NOT EDIT. + +package enttest + +import ( + "context" + + "entgo.io/ent/entc/integration/edgeschema/ent" + // required by schema hooks. + _ "entgo.io/ent/entc/integration/edgeschema/ent/runtime" + + "entgo.io/ent/dialect/sql/schema" +) + +type ( + // TestingT is the interface that is shared between + // testing.T and testing.B and used by enttest. + TestingT interface { + FailNow() + Error(...interface{}) + } + + // Option configures client creation. + Option func(*options) + + options struct { + opts []ent.Option + migrateOpts []schema.MigrateOption + } +) + +// WithOptions forwards options to client creation. +func WithOptions(opts ...ent.Option) Option { + return func(o *options) { + o.opts = append(o.opts, opts...) + } +} + +// WithMigrateOptions forwards options to auto migration. +func WithMigrateOptions(opts ...schema.MigrateOption) Option { + return func(o *options) { + o.migrateOpts = append(o.migrateOpts, opts...) + } +} + +func newOptions(opts []Option) *options { + o := &options{} + for _, opt := range opts { + opt(o) + } + return o +} + +// Open calls ent.Open and auto-run migration. +func Open(t TestingT, driverName, dataSourceName string, opts ...Option) *ent.Client { + o := newOptions(opts) + c, err := ent.Open(driverName, dataSourceName, o.opts...) + if err != nil { + t.Error(err) + t.FailNow() + } + if err := c.Schema.Create(context.Background(), o.migrateOpts...); err != nil { + t.Error(err) + t.FailNow() + } + return c +} + +// NewClient calls ent.NewClient and auto-run migration. +func NewClient(t TestingT, opts ...Option) *ent.Client { + o := newOptions(opts) + c := ent.NewClient(o.opts...) + if err := c.Schema.Create(context.Background(), o.migrateOpts...); err != nil { + t.Error(err) + t.FailNow() + } + return c +} diff --git a/entc/integration/edgeschema/ent/friendship.go b/entc/integration/edgeschema/ent/friendship.go new file mode 100644 index 0000000000..79f30526c1 --- /dev/null +++ b/entc/integration/edgeschema/ent/friendship.go @@ -0,0 +1,186 @@ +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "fmt" + "strings" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/entc/integration/edgeschema/ent/friendship" + "entgo.io/ent/entc/integration/edgeschema/ent/user" +) + +// Friendship is the model entity for the Friendship schema. +type Friendship struct { + config `json:"-"` + // ID of the ent. + ID int `json:"id,omitempty"` + // Weight holds the value of the "weight" field. + Weight int `json:"weight,omitempty"` + // CreatedAt holds the value of the "created_at" field. + CreatedAt time.Time `json:"created_at,omitempty"` + // UserID holds the value of the "user_id" field. + UserID int `json:"user_id,omitempty"` + // FriendID holds the value of the "friend_id" field. + FriendID int `json:"friend_id,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the FriendshipQuery when eager-loading is set. + Edges FriendshipEdges `json:"edges"` +} + +// FriendshipEdges holds the relations/edges for other nodes in the graph. +type FriendshipEdges struct { + // User holds the value of the user edge. + User *User `json:"user,omitempty"` + // Friend holds the value of the friend edge. + Friend *User `json:"friend,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [2]bool +} + +// UserOrErr returns the User value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e FriendshipEdges) UserOrErr() (*User, error) { + if e.loadedTypes[0] { + if e.User == nil { + // The edge user was loaded in eager-loading, + // but was not found. + return nil, &NotFoundError{label: user.Label} + } + return e.User, nil + } + return nil, &NotLoadedError{edge: "user"} +} + +// FriendOrErr returns the Friend value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e FriendshipEdges) FriendOrErr() (*User, error) { + if e.loadedTypes[1] { + if e.Friend == nil { + // The edge friend was loaded in eager-loading, + // but was not found. + return nil, &NotFoundError{label: user.Label} + } + return e.Friend, nil + } + return nil, &NotLoadedError{edge: "friend"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*Friendship) scanValues(columns []string) ([]interface{}, error) { + values := make([]interface{}, len(columns)) + for i := range columns { + switch columns[i] { + case friendship.FieldID, friendship.FieldWeight, friendship.FieldUserID, friendship.FieldFriendID: + values[i] = new(sql.NullInt64) + case friendship.FieldCreatedAt: + values[i] = new(sql.NullTime) + default: + return nil, fmt.Errorf("unexpected column %q for type Friendship", columns[i]) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the Friendship fields. +func (f *Friendship) 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 friendship.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + f.ID = int(value.Int64) + case friendship.FieldWeight: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field weight", values[i]) + } else if value.Valid { + f.Weight = int(value.Int64) + } + case friendship.FieldCreatedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field created_at", values[i]) + } else if value.Valid { + f.CreatedAt = value.Time + } + case friendship.FieldUserID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field user_id", values[i]) + } else if value.Valid { + f.UserID = int(value.Int64) + } + case friendship.FieldFriendID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field friend_id", values[i]) + } else if value.Valid { + f.FriendID = int(value.Int64) + } + } + } + return nil +} + +// QueryUser queries the "user" edge of the Friendship entity. +func (f *Friendship) QueryUser() *UserQuery { + return (&FriendshipClient{config: f.config}).QueryUser(f) +} + +// QueryFriend queries the "friend" edge of the Friendship entity. +func (f *Friendship) QueryFriend() *UserQuery { + return (&FriendshipClient{config: f.config}).QueryFriend(f) +} + +// Update returns a builder for updating this Friendship. +// Note that you need to call Friendship.Unwrap() before calling this method if this Friendship +// was returned from a transaction, and the transaction was committed or rolled back. +func (f *Friendship) Update() *FriendshipUpdateOne { + return (&FriendshipClient{config: f.config}).UpdateOne(f) +} + +// Unwrap unwraps the Friendship 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 (f *Friendship) Unwrap() *Friendship { + tx, ok := f.config.driver.(*txDriver) + if !ok { + panic("ent: Friendship is not a transactional entity") + } + f.config.driver = tx.drv + return f +} + +// String implements the fmt.Stringer. +func (f *Friendship) String() string { + var builder strings.Builder + builder.WriteString("Friendship(") + builder.WriteString(fmt.Sprintf("id=%v, ", f.ID)) + builder.WriteString("weight=") + builder.WriteString(fmt.Sprintf("%v", f.Weight)) + builder.WriteString(", ") + builder.WriteString("created_at=") + builder.WriteString(f.CreatedAt.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("user_id=") + builder.WriteString(fmt.Sprintf("%v", f.UserID)) + builder.WriteString(", ") + builder.WriteString("friend_id=") + builder.WriteString(fmt.Sprintf("%v", f.FriendID)) + builder.WriteByte(')') + return builder.String() +} + +// Friendships is a parsable slice of Friendship. +type Friendships []*Friendship + +func (f Friendships) config(cfg config) { + for _i := range f { + f[_i].config = cfg + } +} diff --git a/entc/integration/edgeschema/ent/friendship/friendship.go b/entc/integration/edgeschema/ent/friendship/friendship.go new file mode 100644 index 0000000000..5c179d5519 --- /dev/null +++ b/entc/integration/edgeschema/ent/friendship/friendship.go @@ -0,0 +1,68 @@ +// Code generated by entc, DO NOT EDIT. + +package friendship + +import ( + "time" +) + +const ( + // Label holds the string label denoting the friendship type in the database. + Label = "friendship" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldWeight holds the string denoting the weight field in the database. + FieldWeight = "weight" + // FieldCreatedAt holds the string denoting the created_at field in the database. + FieldCreatedAt = "created_at" + // FieldUserID holds the string denoting the user_id field in the database. + FieldUserID = "user_id" + // FieldFriendID holds the string denoting the friend_id field in the database. + FieldFriendID = "friend_id" + // EdgeUser holds the string denoting the user edge name in mutations. + EdgeUser = "user" + // EdgeFriend holds the string denoting the friend edge name in mutations. + EdgeFriend = "friend" + // Table holds the table name of the friendship in the database. + Table = "friendships" + // UserTable is the table that holds the user relation/edge. + UserTable = "friendships" + // 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" + // UserColumn is the table column denoting the user relation/edge. + UserColumn = "user_id" + // FriendTable is the table that holds the friend relation/edge. + FriendTable = "friendships" + // FriendInverseTable is the table name for the User entity. + // It exists in this package in order to avoid circular dependency with the "user" package. + FriendInverseTable = "users" + // FriendColumn is the table column denoting the friend relation/edge. + FriendColumn = "friend_id" +) + +// Columns holds all SQL columns for friendship fields. +var Columns = []string{ + FieldID, + FieldWeight, + FieldCreatedAt, + FieldUserID, + FieldFriendID, +} + +// 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 ( + // DefaultWeight holds the default value on creation for the "weight" field. + DefaultWeight int + // DefaultCreatedAt holds the default value on creation for the "created_at" field. + DefaultCreatedAt func() time.Time +) diff --git a/entc/integration/edgeschema/ent/friendship/where.go b/entc/integration/edgeschema/ent/friendship/where.go new file mode 100644 index 0000000000..b9193b69ab --- /dev/null +++ b/entc/integration/edgeschema/ent/friendship/where.go @@ -0,0 +1,458 @@ +// Code generated by entc, DO NOT EDIT. + +package friendship + +import ( + "time" + + "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.Friendship { + return predicate.Friendship(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.Friendship { + return predicate.Friendship(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.Friendship { + return predicate.Friendship(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.Friendship { + return predicate.Friendship(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.Friendship { + return predicate.Friendship(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.Friendship { + return predicate.Friendship(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.Friendship { + return predicate.Friendship(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.Friendship { + return predicate.Friendship(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.Friendship { + return predicate.Friendship(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldID), id)) + }) +} + +// Weight applies equality check predicate on the "weight" field. It's identical to WeightEQ. +func Weight(v int) predicate.Friendship { + return predicate.Friendship(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldWeight), v)) + }) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.Friendship { + return predicate.Friendship(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldCreatedAt), v)) + }) +} + +// UserID applies equality check predicate on the "user_id" field. It's identical to UserIDEQ. +func UserID(v int) predicate.Friendship { + return predicate.Friendship(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldUserID), v)) + }) +} + +// FriendID applies equality check predicate on the "friend_id" field. It's identical to FriendIDEQ. +func FriendID(v int) predicate.Friendship { + return predicate.Friendship(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldFriendID), v)) + }) +} + +// WeightEQ applies the EQ predicate on the "weight" field. +func WeightEQ(v int) predicate.Friendship { + return predicate.Friendship(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldWeight), v)) + }) +} + +// WeightNEQ applies the NEQ predicate on the "weight" field. +func WeightNEQ(v int) predicate.Friendship { + return predicate.Friendship(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldWeight), v)) + }) +} + +// WeightIn applies the In predicate on the "weight" field. +func WeightIn(vs ...int) predicate.Friendship { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Friendship(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(FieldWeight), v...)) + }) +} + +// WeightNotIn applies the NotIn predicate on the "weight" field. +func WeightNotIn(vs ...int) predicate.Friendship { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Friendship(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(FieldWeight), v...)) + }) +} + +// WeightGT applies the GT predicate on the "weight" field. +func WeightGT(v int) predicate.Friendship { + return predicate.Friendship(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldWeight), v)) + }) +} + +// WeightGTE applies the GTE predicate on the "weight" field. +func WeightGTE(v int) predicate.Friendship { + return predicate.Friendship(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldWeight), v)) + }) +} + +// WeightLT applies the LT predicate on the "weight" field. +func WeightLT(v int) predicate.Friendship { + return predicate.Friendship(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldWeight), v)) + }) +} + +// WeightLTE applies the LTE predicate on the "weight" field. +func WeightLTE(v int) predicate.Friendship { + return predicate.Friendship(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldWeight), v)) + }) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.Friendship { + return predicate.Friendship(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldCreatedAt), v)) + }) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.Friendship { + return predicate.Friendship(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldCreatedAt), v)) + }) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.Friendship { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Friendship(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(FieldCreatedAt), v...)) + }) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.Friendship { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Friendship(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(FieldCreatedAt), v...)) + }) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.Friendship { + return predicate.Friendship(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldCreatedAt), v)) + }) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.Friendship { + return predicate.Friendship(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldCreatedAt), v)) + }) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.Friendship { + return predicate.Friendship(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldCreatedAt), v)) + }) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.Friendship { + return predicate.Friendship(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldCreatedAt), v)) + }) +} + +// UserIDEQ applies the EQ predicate on the "user_id" field. +func UserIDEQ(v int) predicate.Friendship { + return predicate.Friendship(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldUserID), v)) + }) +} + +// UserIDNEQ applies the NEQ predicate on the "user_id" field. +func UserIDNEQ(v int) predicate.Friendship { + return predicate.Friendship(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldUserID), v)) + }) +} + +// UserIDIn applies the In predicate on the "user_id" field. +func UserIDIn(vs ...int) predicate.Friendship { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Friendship(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(FieldUserID), v...)) + }) +} + +// UserIDNotIn applies the NotIn predicate on the "user_id" field. +func UserIDNotIn(vs ...int) predicate.Friendship { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Friendship(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(FieldUserID), v...)) + }) +} + +// FriendIDEQ applies the EQ predicate on the "friend_id" field. +func FriendIDEQ(v int) predicate.Friendship { + return predicate.Friendship(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldFriendID), v)) + }) +} + +// FriendIDNEQ applies the NEQ predicate on the "friend_id" field. +func FriendIDNEQ(v int) predicate.Friendship { + return predicate.Friendship(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldFriendID), v)) + }) +} + +// FriendIDIn applies the In predicate on the "friend_id" field. +func FriendIDIn(vs ...int) predicate.Friendship { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Friendship(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(FieldFriendID), v...)) + }) +} + +// FriendIDNotIn applies the NotIn predicate on the "friend_id" field. +func FriendIDNotIn(vs ...int) predicate.Friendship { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Friendship(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(FieldFriendID), v...)) + }) +} + +// HasUser applies the HasEdge predicate on the "user" edge. +func HasUser() predicate.Friendship { + return predicate.Friendship(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(UserTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, UserTable, UserColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasUserWith applies the HasEdge predicate on the "user" edge with a given conditions (other predicates). +func HasUserWith(preds ...predicate.User) predicate.Friendship { + return predicate.Friendship(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(UserInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, UserTable, UserColumn), + ) + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasFriend applies the HasEdge predicate on the "friend" edge. +func HasFriend() predicate.Friendship { + return predicate.Friendship(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(FriendTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, FriendTable, FriendColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasFriendWith applies the HasEdge predicate on the "friend" edge with a given conditions (other predicates). +func HasFriendWith(preds ...predicate.User) predicate.Friendship { + return predicate.Friendship(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(FriendInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, FriendTable, FriendColumn), + ) + 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.Friendship) predicate.Friendship { + return predicate.Friendship(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.Friendship) predicate.Friendship { + return predicate.Friendship(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.Friendship) predicate.Friendship { + return predicate.Friendship(func(s *sql.Selector) { + p(s.Not()) + }) +} diff --git a/entc/integration/edgeschema/ent/friendship_create.go b/entc/integration/edgeschema/ent/friendship_create.go new file mode 100644 index 0000000000..67b2d75ab6 --- /dev/null +++ b/entc/integration/edgeschema/ent/friendship_create.go @@ -0,0 +1,349 @@ +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/edgeschema/ent/friendship" + "entgo.io/ent/entc/integration/edgeschema/ent/user" + "entgo.io/ent/schema/field" +) + +// FriendshipCreate is the builder for creating a Friendship entity. +type FriendshipCreate struct { + config + mutation *FriendshipMutation + hooks []Hook +} + +// SetWeight sets the "weight" field. +func (fc *FriendshipCreate) SetWeight(i int) *FriendshipCreate { + fc.mutation.SetWeight(i) + return fc +} + +// SetNillableWeight sets the "weight" field if the given value is not nil. +func (fc *FriendshipCreate) SetNillableWeight(i *int) *FriendshipCreate { + if i != nil { + fc.SetWeight(*i) + } + return fc +} + +// SetCreatedAt sets the "created_at" field. +func (fc *FriendshipCreate) SetCreatedAt(t time.Time) *FriendshipCreate { + fc.mutation.SetCreatedAt(t) + return fc +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (fc *FriendshipCreate) SetNillableCreatedAt(t *time.Time) *FriendshipCreate { + if t != nil { + fc.SetCreatedAt(*t) + } + return fc +} + +// SetUserID sets the "user_id" field. +func (fc *FriendshipCreate) SetUserID(i int) *FriendshipCreate { + fc.mutation.SetUserID(i) + return fc +} + +// SetFriendID sets the "friend_id" field. +func (fc *FriendshipCreate) SetFriendID(i int) *FriendshipCreate { + fc.mutation.SetFriendID(i) + return fc +} + +// SetUser sets the "user" edge to the User entity. +func (fc *FriendshipCreate) SetUser(u *User) *FriendshipCreate { + return fc.SetUserID(u.ID) +} + +// SetFriend sets the "friend" edge to the User entity. +func (fc *FriendshipCreate) SetFriend(u *User) *FriendshipCreate { + return fc.SetFriendID(u.ID) +} + +// Mutation returns the FriendshipMutation object of the builder. +func (fc *FriendshipCreate) Mutation() *FriendshipMutation { + return fc.mutation +} + +// Save creates the Friendship in the database. +func (fc *FriendshipCreate) Save(ctx context.Context) (*Friendship, error) { + var ( + err error + node *Friendship + ) + fc.defaults() + if len(fc.hooks) == 0 { + if err = fc.check(); err != nil { + return nil, err + } + node, err = fc.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*FriendshipMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err = fc.check(); err != nil { + return nil, err + } + fc.mutation = mutation + if node, err = fc.sqlSave(ctx); err != nil { + return nil, err + } + mutation.id = &node.ID + mutation.done = true + return node, err + }) + for i := len(fc.hooks) - 1; i >= 0; i-- { + if fc.hooks[i] == nil { + return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = fc.hooks[i](mut) + } + v, err := mut.Mutate(ctx, fc.mutation) + if err != nil { + return nil, err + } + nv, ok := v.(*Friendship) + if !ok { + return nil, fmt.Errorf("unexpected node type %T returned from FriendshipMutation", v) + } + node = nv + } + return node, err +} + +// SaveX calls Save and panics if Save returns an error. +func (fc *FriendshipCreate) SaveX(ctx context.Context) *Friendship { + v, err := fc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (fc *FriendshipCreate) Exec(ctx context.Context) error { + _, err := fc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (fc *FriendshipCreate) ExecX(ctx context.Context) { + if err := fc.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (fc *FriendshipCreate) defaults() { + if _, ok := fc.mutation.Weight(); !ok { + v := friendship.DefaultWeight + fc.mutation.SetWeight(v) + } + if _, ok := fc.mutation.CreatedAt(); !ok { + v := friendship.DefaultCreatedAt() + fc.mutation.SetCreatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (fc *FriendshipCreate) check() error { + if _, ok := fc.mutation.Weight(); !ok { + return &ValidationError{Name: "weight", err: errors.New(`ent: missing required field "Friendship.weight"`)} + } + if _, ok := fc.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "Friendship.created_at"`)} + } + if _, ok := fc.mutation.UserID(); !ok { + return &ValidationError{Name: "user_id", err: errors.New(`ent: missing required field "Friendship.user_id"`)} + } + if _, ok := fc.mutation.FriendID(); !ok { + return &ValidationError{Name: "friend_id", err: errors.New(`ent: missing required field "Friendship.friend_id"`)} + } + if _, ok := fc.mutation.UserID(); !ok { + return &ValidationError{Name: "user", err: errors.New(`ent: missing required edge "Friendship.user"`)} + } + if _, ok := fc.mutation.FriendID(); !ok { + return &ValidationError{Name: "friend", err: errors.New(`ent: missing required edge "Friendship.friend"`)} + } + return nil +} + +func (fc *FriendshipCreate) sqlSave(ctx context.Context) (*Friendship, error) { + _node, _spec := fc.createSpec() + if err := sqlgraph.CreateNode(ctx, fc.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return nil, err + } + id := _spec.ID.Value.(int64) + _node.ID = int(id) + return _node, nil +} + +func (fc *FriendshipCreate) createSpec() (*Friendship, *sqlgraph.CreateSpec) { + var ( + _node = &Friendship{config: fc.config} + _spec = &sqlgraph.CreateSpec{ + Table: friendship.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: friendship.FieldID, + }, + } + ) + if value, ok := fc.mutation.Weight(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: friendship.FieldWeight, + }) + _node.Weight = value + } + if value, ok := fc.mutation.CreatedAt(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: friendship.FieldCreatedAt, + }) + _node.CreatedAt = value + } + if nodes := fc.mutation.UserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: friendship.UserTable, + Columns: []string{friendship.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.UserID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := fc.mutation.FriendIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: friendship.FriendTable, + Columns: []string{friendship.FriendColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.FriendID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// FriendshipCreateBulk is the builder for creating many Friendship entities in bulk. +type FriendshipCreateBulk struct { + config + builders []*FriendshipCreate +} + +// Save creates the Friendship entities in the database. +func (fcb *FriendshipCreateBulk) Save(ctx context.Context) ([]*Friendship, error) { + specs := make([]*sqlgraph.CreateSpec, len(fcb.builders)) + nodes := make([]*Friendship, len(fcb.builders)) + mutators := make([]Mutator, len(fcb.builders)) + for i := range fcb.builders { + func(i int, root context.Context) { + builder := fcb.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*FriendshipMutation) + 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, fcb.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, fcb.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), 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, fcb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (fcb *FriendshipCreateBulk) SaveX(ctx context.Context) []*Friendship { + v, err := fcb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (fcb *FriendshipCreateBulk) Exec(ctx context.Context) error { + _, err := fcb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (fcb *FriendshipCreateBulk) ExecX(ctx context.Context) { + if err := fcb.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/entc/integration/edgeschema/ent/friendship_delete.go b/entc/integration/edgeschema/ent/friendship_delete.go new file mode 100644 index 0000000000..82ddac2b0d --- /dev/null +++ b/entc/integration/edgeschema/ent/friendship_delete.go @@ -0,0 +1,111 @@ +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "fmt" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/edgeschema/ent/friendship" + "entgo.io/ent/entc/integration/edgeschema/ent/predicate" + "entgo.io/ent/schema/field" +) + +// FriendshipDelete is the builder for deleting a Friendship entity. +type FriendshipDelete struct { + config + hooks []Hook + mutation *FriendshipMutation +} + +// Where appends a list predicates to the FriendshipDelete builder. +func (fd *FriendshipDelete) Where(ps ...predicate.Friendship) *FriendshipDelete { + fd.mutation.Where(ps...) + return fd +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (fd *FriendshipDelete) Exec(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(fd.hooks) == 0 { + affected, err = fd.sqlExec(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*FriendshipMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + fd.mutation = mutation + affected, err = fd.sqlExec(ctx) + mutation.done = true + return affected, err + }) + for i := len(fd.hooks) - 1; i >= 0; i-- { + if fd.hooks[i] == nil { + return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = fd.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, fd.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// ExecX is like Exec, but panics if an error occurs. +func (fd *FriendshipDelete) ExecX(ctx context.Context) int { + n, err := fd.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (fd *FriendshipDelete) sqlExec(ctx context.Context) (int, error) { + _spec := &sqlgraph.DeleteSpec{ + Node: &sqlgraph.NodeSpec{ + Table: friendship.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: friendship.FieldID, + }, + }, + } + if ps := fd.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return sqlgraph.DeleteNodes(ctx, fd.driver, _spec) +} + +// FriendshipDeleteOne is the builder for deleting a single Friendship entity. +type FriendshipDeleteOne struct { + fd *FriendshipDelete +} + +// Exec executes the deletion query. +func (fdo *FriendshipDeleteOne) Exec(ctx context.Context) error { + n, err := fdo.fd.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{friendship.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (fdo *FriendshipDeleteOne) ExecX(ctx context.Context) { + fdo.fd.ExecX(ctx) +} diff --git a/entc/integration/edgeschema/ent/friendship_query.go b/entc/integration/edgeschema/ent/friendship_query.go new file mode 100644 index 0000000000..da1737e0bb --- /dev/null +++ b/entc/integration/edgeschema/ent/friendship_query.go @@ -0,0 +1,658 @@ +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "fmt" + "math" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/edgeschema/ent/friendship" + "entgo.io/ent/entc/integration/edgeschema/ent/predicate" + "entgo.io/ent/entc/integration/edgeschema/ent/user" + "entgo.io/ent/schema/field" +) + +// FriendshipQuery is the builder for querying Friendship entities. +type FriendshipQuery struct { + config + limit *int + offset *int + unique *bool + order []OrderFunc + fields []string + predicates []predicate.Friendship + // eager-loading edges. + withUser *UserQuery + withFriend *UserQuery + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the FriendshipQuery builder. +func (fq *FriendshipQuery) Where(ps ...predicate.Friendship) *FriendshipQuery { + fq.predicates = append(fq.predicates, ps...) + return fq +} + +// Limit adds a limit step to the query. +func (fq *FriendshipQuery) Limit(limit int) *FriendshipQuery { + fq.limit = &limit + return fq +} + +// Offset adds an offset step to the query. +func (fq *FriendshipQuery) Offset(offset int) *FriendshipQuery { + fq.offset = &offset + return fq +} + +// 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 (fq *FriendshipQuery) Unique(unique bool) *FriendshipQuery { + fq.unique = &unique + return fq +} + +// Order adds an order step to the query. +func (fq *FriendshipQuery) Order(o ...OrderFunc) *FriendshipQuery { + fq.order = append(fq.order, o...) + return fq +} + +// QueryUser chains the current query on the "user" edge. +func (fq *FriendshipQuery) QueryUser() *UserQuery { + query := &UserQuery{config: fq.config} + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := fq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := fq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(friendship.Table, friendship.FieldID, selector), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, friendship.UserTable, friendship.UserColumn), + ) + fromU = sqlgraph.SetNeighbors(fq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryFriend chains the current query on the "friend" edge. +func (fq *FriendshipQuery) QueryFriend() *UserQuery { + query := &UserQuery{config: fq.config} + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := fq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := fq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(friendship.Table, friendship.FieldID, selector), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, friendship.FriendTable, friendship.FriendColumn), + ) + fromU = sqlgraph.SetNeighbors(fq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first Friendship entity from the query. +// Returns a *NotFoundError when no Friendship was found. +func (fq *FriendshipQuery) First(ctx context.Context) (*Friendship, error) { + nodes, err := fq.Limit(1).All(ctx) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{friendship.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (fq *FriendshipQuery) FirstX(ctx context.Context) *Friendship { + node, err := fq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first Friendship ID from the query. +// Returns a *NotFoundError when no Friendship ID was found. +func (fq *FriendshipQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = fq.Limit(1).IDs(ctx); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{friendship.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (fq *FriendshipQuery) FirstIDX(ctx context.Context) int { + id, err := fq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single Friendship entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Friendship entity is found. +// Returns a *NotFoundError when no Friendship entities are found. +func (fq *FriendshipQuery) Only(ctx context.Context) (*Friendship, error) { + nodes, err := fq.Limit(2).All(ctx) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{friendship.Label} + default: + return nil, &NotSingularError{friendship.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (fq *FriendshipQuery) OnlyX(ctx context.Context) *Friendship { + node, err := fq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only Friendship ID in the query. +// Returns a *NotSingularError when more than one Friendship ID is found. +// Returns a *NotFoundError when no entities are found. +func (fq *FriendshipQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = fq.Limit(2).IDs(ctx); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{friendship.Label} + default: + err = &NotSingularError{friendship.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (fq *FriendshipQuery) OnlyIDX(ctx context.Context) int { + id, err := fq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of Friendships. +func (fq *FriendshipQuery) All(ctx context.Context) ([]*Friendship, error) { + if err := fq.prepareQuery(ctx); err != nil { + return nil, err + } + return fq.sqlAll(ctx) +} + +// AllX is like All, but panics if an error occurs. +func (fq *FriendshipQuery) AllX(ctx context.Context) []*Friendship { + nodes, err := fq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of Friendship IDs. +func (fq *FriendshipQuery) IDs(ctx context.Context) ([]int, error) { + var ids []int + if err := fq.Select(friendship.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (fq *FriendshipQuery) IDsX(ctx context.Context) []int { + ids, err := fq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (fq *FriendshipQuery) Count(ctx context.Context) (int, error) { + if err := fq.prepareQuery(ctx); err != nil { + return 0, err + } + return fq.sqlCount(ctx) +} + +// CountX is like Count, but panics if an error occurs. +func (fq *FriendshipQuery) CountX(ctx context.Context) int { + count, err := fq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (fq *FriendshipQuery) Exist(ctx context.Context) (bool, error) { + if err := fq.prepareQuery(ctx); err != nil { + return false, err + } + return fq.sqlExist(ctx) +} + +// ExistX is like Exist, but panics if an error occurs. +func (fq *FriendshipQuery) ExistX(ctx context.Context) bool { + exist, err := fq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the FriendshipQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (fq *FriendshipQuery) Clone() *FriendshipQuery { + if fq == nil { + return nil + } + return &FriendshipQuery{ + config: fq.config, + limit: fq.limit, + offset: fq.offset, + order: append([]OrderFunc{}, fq.order...), + predicates: append([]predicate.Friendship{}, fq.predicates...), + withUser: fq.withUser.Clone(), + withFriend: fq.withFriend.Clone(), + // clone intermediate query. + sql: fq.sql.Clone(), + path: fq.path, + unique: fq.unique, + } +} + +// WithUser tells the query-builder to eager-load the nodes that are connected to +// the "user" edge. The optional arguments are used to configure the query builder of the edge. +func (fq *FriendshipQuery) WithUser(opts ...func(*UserQuery)) *FriendshipQuery { + query := &UserQuery{config: fq.config} + for _, opt := range opts { + opt(query) + } + fq.withUser = query + return fq +} + +// WithFriend tells the query-builder to eager-load the nodes that are connected to +// the "friend" edge. The optional arguments are used to configure the query builder of the edge. +func (fq *FriendshipQuery) WithFriend(opts ...func(*UserQuery)) *FriendshipQuery { + query := &UserQuery{config: fq.config} + for _, opt := range opts { + opt(query) + } + fq.withFriend = query + return fq +} + +// 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 { +// Weight int `json:"weight,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.Friendship.Query(). +// GroupBy(friendship.FieldWeight). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +// +func (fq *FriendshipQuery) GroupBy(field string, fields ...string) *FriendshipGroupBy { + grbuild := &FriendshipGroupBy{config: fq.config} + grbuild.fields = append([]string{field}, fields...) + grbuild.path = func(ctx context.Context) (prev *sql.Selector, err error) { + if err := fq.prepareQuery(ctx); err != nil { + return nil, err + } + return fq.sqlQuery(ctx), nil + } + grbuild.label = friendship.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 { +// Weight int `json:"weight,omitempty"` +// } +// +// client.Friendship.Query(). +// Select(friendship.FieldWeight). +// Scan(ctx, &v) +// +func (fq *FriendshipQuery) Select(fields ...string) *FriendshipSelect { + fq.fields = append(fq.fields, fields...) + selbuild := &FriendshipSelect{FriendshipQuery: fq} + selbuild.label = friendship.Label + selbuild.flds, selbuild.scan = &fq.fields, selbuild.Scan + return selbuild +} + +func (fq *FriendshipQuery) prepareQuery(ctx context.Context) error { + for _, f := range fq.fields { + if !friendship.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if fq.path != nil { + prev, err := fq.path(ctx) + if err != nil { + return err + } + fq.sql = prev + } + return nil +} + +func (fq *FriendshipQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Friendship, error) { + var ( + nodes = []*Friendship{} + _spec = fq.querySpec() + loadedTypes = [2]bool{ + fq.withUser != nil, + fq.withFriend != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]interface{}, error) { + return (*Friendship).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []interface{}) error { + node := &Friendship{config: fq.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, fq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + + if query := fq.withUser; query != nil { + ids := make([]int, 0, len(nodes)) + nodeids := make(map[int][]*Friendship) + for i := range nodes { + fk := nodes[i].UserID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + query.Where(user.IDIn(ids...)) + neighbors, err := query.All(ctx) + if err != nil { + return nil, err + } + for _, n := range neighbors { + nodes, ok := nodeids[n.ID] + if !ok { + return nil, fmt.Errorf(`unexpected foreign-key "user_id" returned %v`, n.ID) + } + for i := range nodes { + nodes[i].Edges.User = n + } + } + } + + if query := fq.withFriend; query != nil { + ids := make([]int, 0, len(nodes)) + nodeids := make(map[int][]*Friendship) + for i := range nodes { + fk := nodes[i].FriendID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + query.Where(user.IDIn(ids...)) + neighbors, err := query.All(ctx) + if err != nil { + return nil, err + } + for _, n := range neighbors { + nodes, ok := nodeids[n.ID] + if !ok { + return nil, fmt.Errorf(`unexpected foreign-key "friend_id" returned %v`, n.ID) + } + for i := range nodes { + nodes[i].Edges.Friend = n + } + } + } + + return nodes, nil +} + +func (fq *FriendshipQuery) sqlCount(ctx context.Context) (int, error) { + _spec := fq.querySpec() + _spec.Node.Columns = fq.fields + if len(fq.fields) > 0 { + _spec.Unique = fq.unique != nil && *fq.unique + } + return sqlgraph.CountNodes(ctx, fq.driver, _spec) +} + +func (fq *FriendshipQuery) sqlExist(ctx context.Context) (bool, error) { + n, err := fq.sqlCount(ctx) + if err != nil { + return false, fmt.Errorf("ent: check existence: %w", err) + } + return n > 0, nil +} + +func (fq *FriendshipQuery) querySpec() *sqlgraph.QuerySpec { + _spec := &sqlgraph.QuerySpec{ + Node: &sqlgraph.NodeSpec{ + Table: friendship.Table, + Columns: friendship.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: friendship.FieldID, + }, + }, + From: fq.sql, + Unique: true, + } + if unique := fq.unique; unique != nil { + _spec.Unique = *unique + } + if fields := fq.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, friendship.FieldID) + for i := range fields { + if fields[i] != friendship.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := fq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := fq.limit; limit != nil { + _spec.Limit = *limit + } + if offset := fq.offset; offset != nil { + _spec.Offset = *offset + } + if ps := fq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (fq *FriendshipQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(fq.driver.Dialect()) + t1 := builder.Table(friendship.Table) + columns := fq.fields + if len(columns) == 0 { + columns = friendship.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if fq.sql != nil { + selector = fq.sql + selector.Select(selector.Columns(columns...)...) + } + if fq.unique != nil && *fq.unique { + selector.Distinct() + } + for _, p := range fq.predicates { + p(selector) + } + for _, p := range fq.order { + p(selector) + } + if offset := fq.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 := fq.limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// FriendshipGroupBy is the group-by builder for Friendship entities. +type FriendshipGroupBy 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 (fgb *FriendshipGroupBy) Aggregate(fns ...AggregateFunc) *FriendshipGroupBy { + fgb.fns = append(fgb.fns, fns...) + return fgb +} + +// Scan applies the group-by query and scans the result into the given value. +func (fgb *FriendshipGroupBy) Scan(ctx context.Context, v interface{}) error { + query, err := fgb.path(ctx) + if err != nil { + return err + } + fgb.sql = query + return fgb.sqlScan(ctx, v) +} + +func (fgb *FriendshipGroupBy) sqlScan(ctx context.Context, v interface{}) error { + for _, f := range fgb.fields { + if !friendship.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)} + } + } + selector := fgb.sqlQuery() + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := fgb.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +func (fgb *FriendshipGroupBy) sqlQuery() *sql.Selector { + selector := fgb.sql.Select() + aggregation := make([]string, 0, len(fgb.fns)) + for _, fn := range fgb.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(fgb.fields)+len(fgb.fns)) + for _, f := range fgb.fields { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + return selector.GroupBy(selector.Columns(fgb.fields...)...) +} + +// FriendshipSelect is the builder for selecting fields of Friendship entities. +type FriendshipSelect struct { + *FriendshipQuery + selector + // intermediate query (i.e. traversal path). + sql *sql.Selector +} + +// Scan applies the selector query and scans the result into the given value. +func (fs *FriendshipSelect) Scan(ctx context.Context, v interface{}) error { + if err := fs.prepareQuery(ctx); err != nil { + return err + } + fs.sql = fs.FriendshipQuery.sqlQuery(ctx) + return fs.sqlScan(ctx, v) +} + +func (fs *FriendshipSelect) sqlScan(ctx context.Context, v interface{}) error { + rows := &sql.Rows{} + query, args := fs.sql.Query() + if err := fs.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/friendship_update.go b/entc/integration/edgeschema/ent/friendship_update.go new file mode 100644 index 0000000000..db46956a88 --- /dev/null +++ b/entc/integration/edgeschema/ent/friendship_update.go @@ -0,0 +1,601 @@ +// Code generated by entc, 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/friendship" + "entgo.io/ent/entc/integration/edgeschema/ent/predicate" + "entgo.io/ent/entc/integration/edgeschema/ent/user" + "entgo.io/ent/schema/field" +) + +// FriendshipUpdate is the builder for updating Friendship entities. +type FriendshipUpdate struct { + config + hooks []Hook + mutation *FriendshipMutation +} + +// Where appends a list predicates to the FriendshipUpdate builder. +func (fu *FriendshipUpdate) Where(ps ...predicate.Friendship) *FriendshipUpdate { + fu.mutation.Where(ps...) + return fu +} + +// SetWeight sets the "weight" field. +func (fu *FriendshipUpdate) SetWeight(i int) *FriendshipUpdate { + fu.mutation.ResetWeight() + fu.mutation.SetWeight(i) + return fu +} + +// SetNillableWeight sets the "weight" field if the given value is not nil. +func (fu *FriendshipUpdate) SetNillableWeight(i *int) *FriendshipUpdate { + if i != nil { + fu.SetWeight(*i) + } + return fu +} + +// AddWeight adds i to the "weight" field. +func (fu *FriendshipUpdate) AddWeight(i int) *FriendshipUpdate { + fu.mutation.AddWeight(i) + return fu +} + +// SetCreatedAt sets the "created_at" field. +func (fu *FriendshipUpdate) SetCreatedAt(t time.Time) *FriendshipUpdate { + fu.mutation.SetCreatedAt(t) + return fu +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (fu *FriendshipUpdate) SetNillableCreatedAt(t *time.Time) *FriendshipUpdate { + if t != nil { + fu.SetCreatedAt(*t) + } + return fu +} + +// SetUserID sets the "user_id" field. +func (fu *FriendshipUpdate) SetUserID(i int) *FriendshipUpdate { + fu.mutation.SetUserID(i) + return fu +} + +// SetFriendID sets the "friend_id" field. +func (fu *FriendshipUpdate) SetFriendID(i int) *FriendshipUpdate { + fu.mutation.SetFriendID(i) + return fu +} + +// SetUser sets the "user" edge to the User entity. +func (fu *FriendshipUpdate) SetUser(u *User) *FriendshipUpdate { + return fu.SetUserID(u.ID) +} + +// SetFriend sets the "friend" edge to the User entity. +func (fu *FriendshipUpdate) SetFriend(u *User) *FriendshipUpdate { + return fu.SetFriendID(u.ID) +} + +// Mutation returns the FriendshipMutation object of the builder. +func (fu *FriendshipUpdate) Mutation() *FriendshipMutation { + return fu.mutation +} + +// ClearUser clears the "user" edge to the User entity. +func (fu *FriendshipUpdate) ClearUser() *FriendshipUpdate { + fu.mutation.ClearUser() + return fu +} + +// ClearFriend clears the "friend" edge to the User entity. +func (fu *FriendshipUpdate) ClearFriend() *FriendshipUpdate { + fu.mutation.ClearFriend() + return fu +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (fu *FriendshipUpdate) Save(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(fu.hooks) == 0 { + if err = fu.check(); err != nil { + return 0, err + } + affected, err = fu.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*FriendshipMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err = fu.check(); err != nil { + return 0, err + } + fu.mutation = mutation + affected, err = fu.sqlSave(ctx) + mutation.done = true + return affected, err + }) + for i := len(fu.hooks) - 1; i >= 0; i-- { + if fu.hooks[i] == nil { + return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = fu.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, fu.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// SaveX is like Save, but panics if an error occurs. +func (fu *FriendshipUpdate) SaveX(ctx context.Context) int { + affected, err := fu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (fu *FriendshipUpdate) Exec(ctx context.Context) error { + _, err := fu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (fu *FriendshipUpdate) ExecX(ctx context.Context) { + if err := fu.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (fu *FriendshipUpdate) check() error { + if _, ok := fu.mutation.UserID(); fu.mutation.UserCleared() && !ok { + return errors.New(`ent: clearing a required unique edge "Friendship.user"`) + } + if _, ok := fu.mutation.FriendID(); fu.mutation.FriendCleared() && !ok { + return errors.New(`ent: clearing a required unique edge "Friendship.friend"`) + } + return nil +} + +func (fu *FriendshipUpdate) sqlSave(ctx context.Context) (n int, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: friendship.Table, + Columns: friendship.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: friendship.FieldID, + }, + }, + } + if ps := fu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := fu.mutation.Weight(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: friendship.FieldWeight, + }) + } + if value, ok := fu.mutation.AddedWeight(); ok { + _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: friendship.FieldWeight, + }) + } + if value, ok := fu.mutation.CreatedAt(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: friendship.FieldCreatedAt, + }) + } + if fu.mutation.UserCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: friendship.UserTable, + Columns: []string{friendship.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := fu.mutation.UserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: friendship.UserTable, + Columns: []string{friendship.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if fu.mutation.FriendCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: friendship.FriendTable, + Columns: []string{friendship.FriendColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := fu.mutation.FriendIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: friendship.FriendTable, + Columns: []string{friendship.FriendColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if n, err = sqlgraph.UpdateNodes(ctx, fu.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{friendship.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return 0, err + } + return n, nil +} + +// FriendshipUpdateOne is the builder for updating a single Friendship entity. +type FriendshipUpdateOne struct { + config + fields []string + hooks []Hook + mutation *FriendshipMutation +} + +// SetWeight sets the "weight" field. +func (fuo *FriendshipUpdateOne) SetWeight(i int) *FriendshipUpdateOne { + fuo.mutation.ResetWeight() + fuo.mutation.SetWeight(i) + return fuo +} + +// SetNillableWeight sets the "weight" field if the given value is not nil. +func (fuo *FriendshipUpdateOne) SetNillableWeight(i *int) *FriendshipUpdateOne { + if i != nil { + fuo.SetWeight(*i) + } + return fuo +} + +// AddWeight adds i to the "weight" field. +func (fuo *FriendshipUpdateOne) AddWeight(i int) *FriendshipUpdateOne { + fuo.mutation.AddWeight(i) + return fuo +} + +// SetCreatedAt sets the "created_at" field. +func (fuo *FriendshipUpdateOne) SetCreatedAt(t time.Time) *FriendshipUpdateOne { + fuo.mutation.SetCreatedAt(t) + return fuo +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (fuo *FriendshipUpdateOne) SetNillableCreatedAt(t *time.Time) *FriendshipUpdateOne { + if t != nil { + fuo.SetCreatedAt(*t) + } + return fuo +} + +// SetUserID sets the "user_id" field. +func (fuo *FriendshipUpdateOne) SetUserID(i int) *FriendshipUpdateOne { + fuo.mutation.SetUserID(i) + return fuo +} + +// SetFriendID sets the "friend_id" field. +func (fuo *FriendshipUpdateOne) SetFriendID(i int) *FriendshipUpdateOne { + fuo.mutation.SetFriendID(i) + return fuo +} + +// SetUser sets the "user" edge to the User entity. +func (fuo *FriendshipUpdateOne) SetUser(u *User) *FriendshipUpdateOne { + return fuo.SetUserID(u.ID) +} + +// SetFriend sets the "friend" edge to the User entity. +func (fuo *FriendshipUpdateOne) SetFriend(u *User) *FriendshipUpdateOne { + return fuo.SetFriendID(u.ID) +} + +// Mutation returns the FriendshipMutation object of the builder. +func (fuo *FriendshipUpdateOne) Mutation() *FriendshipMutation { + return fuo.mutation +} + +// ClearUser clears the "user" edge to the User entity. +func (fuo *FriendshipUpdateOne) ClearUser() *FriendshipUpdateOne { + fuo.mutation.ClearUser() + return fuo +} + +// ClearFriend clears the "friend" edge to the User entity. +func (fuo *FriendshipUpdateOne) ClearFriend() *FriendshipUpdateOne { + fuo.mutation.ClearFriend() + return fuo +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (fuo *FriendshipUpdateOne) Select(field string, fields ...string) *FriendshipUpdateOne { + fuo.fields = append([]string{field}, fields...) + return fuo +} + +// Save executes the query and returns the updated Friendship entity. +func (fuo *FriendshipUpdateOne) Save(ctx context.Context) (*Friendship, error) { + var ( + err error + node *Friendship + ) + if len(fuo.hooks) == 0 { + if err = fuo.check(); err != nil { + return nil, err + } + node, err = fuo.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*FriendshipMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err = fuo.check(); err != nil { + return nil, err + } + fuo.mutation = mutation + node, err = fuo.sqlSave(ctx) + mutation.done = true + return node, err + }) + for i := len(fuo.hooks) - 1; i >= 0; i-- { + if fuo.hooks[i] == nil { + return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = fuo.hooks[i](mut) + } + v, err := mut.Mutate(ctx, fuo.mutation) + if err != nil { + return nil, err + } + nv, ok := v.(*Friendship) + if !ok { + return nil, fmt.Errorf("unexpected node type %T returned from FriendshipMutation", v) + } + node = nv + } + return node, err +} + +// SaveX is like Save, but panics if an error occurs. +func (fuo *FriendshipUpdateOne) SaveX(ctx context.Context) *Friendship { + node, err := fuo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (fuo *FriendshipUpdateOne) Exec(ctx context.Context) error { + _, err := fuo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (fuo *FriendshipUpdateOne) ExecX(ctx context.Context) { + if err := fuo.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (fuo *FriendshipUpdateOne) check() error { + if _, ok := fuo.mutation.UserID(); fuo.mutation.UserCleared() && !ok { + return errors.New(`ent: clearing a required unique edge "Friendship.user"`) + } + if _, ok := fuo.mutation.FriendID(); fuo.mutation.FriendCleared() && !ok { + return errors.New(`ent: clearing a required unique edge "Friendship.friend"`) + } + return nil +} + +func (fuo *FriendshipUpdateOne) sqlSave(ctx context.Context) (_node *Friendship, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: friendship.Table, + Columns: friendship.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: friendship.FieldID, + }, + }, + } + id, ok := fuo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Friendship.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := fuo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, friendship.FieldID) + for _, f := range fields { + if !friendship.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != friendship.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := fuo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := fuo.mutation.Weight(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: friendship.FieldWeight, + }) + } + if value, ok := fuo.mutation.AddedWeight(); ok { + _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: friendship.FieldWeight, + }) + } + if value, ok := fuo.mutation.CreatedAt(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: friendship.FieldCreatedAt, + }) + } + if fuo.mutation.UserCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: friendship.UserTable, + Columns: []string{friendship.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := fuo.mutation.UserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: friendship.UserTable, + Columns: []string{friendship.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if fuo.mutation.FriendCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: friendship.FriendTable, + Columns: []string{friendship.FriendColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := fuo.mutation.FriendIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: friendship.FriendTable, + Columns: []string{friendship.FriendColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &Friendship{config: fuo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, fuo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{friendship.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return nil, err + } + return _node, nil +} diff --git a/entc/integration/edgeschema/ent/generate.go b/entc/integration/edgeschema/ent/generate.go new file mode 100644 index 0000000000..23754cfcbd --- /dev/null +++ b/entc/integration/edgeschema/ent/generate.go @@ -0,0 +1,7 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +package ent + +//go:generate go run -mod=mod entgo.io/ent/cmd/ent generate ./schema diff --git a/entc/integration/edgeschema/ent/group.go b/entc/integration/edgeschema/ent/group.go new file mode 100644 index 0000000000..86ee882fb5 --- /dev/null +++ b/entc/integration/edgeschema/ent/group.go @@ -0,0 +1,141 @@ +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "fmt" + "strings" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/entc/integration/edgeschema/ent/group" +) + +// Group is the model entity for the Group schema. +type Group struct { + config `json:"-"` + // ID of the ent. + ID int `json:"id,omitempty"` + // Name holds the value of the "name" field. + Name string `json:"name,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the GroupQuery when eager-loading is set. + Edges GroupEdges `json:"edges"` +} + +// GroupEdges holds the relations/edges for other nodes in the graph. +type GroupEdges struct { + // Users holds the value of the users edge. + Users []*User `json:"users,omitempty"` + // JoinedUsers holds the value of the joined_users edge. + JoinedUsers []*UserGroup `json:"joined_users,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [2]bool +} + +// UsersOrErr returns the Users value or an error if the edge +// was not loaded in eager-loading. +func (e GroupEdges) UsersOrErr() ([]*User, error) { + if e.loadedTypes[0] { + return e.Users, nil + } + return nil, &NotLoadedError{edge: "users"} +} + +// JoinedUsersOrErr returns the JoinedUsers value or an error if the edge +// was not loaded in eager-loading. +func (e GroupEdges) JoinedUsersOrErr() ([]*UserGroup, error) { + if e.loadedTypes[1] { + return e.JoinedUsers, nil + } + return nil, &NotLoadedError{edge: "joined_users"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*Group) scanValues(columns []string) ([]interface{}, error) { + values := make([]interface{}, len(columns)) + for i := range columns { + switch columns[i] { + case group.FieldID: + values[i] = new(sql.NullInt64) + case group.FieldName: + values[i] = new(sql.NullString) + default: + return nil, fmt.Errorf("unexpected column %q for type Group", columns[i]) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the Group fields. +func (gr *Group) 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 group.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + gr.ID = int(value.Int64) + case group.FieldName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field name", values[i]) + } else if value.Valid { + gr.Name = value.String + } + } + } + return nil +} + +// QueryUsers queries the "users" edge of the Group entity. +func (gr *Group) QueryUsers() *UserQuery { + return (&GroupClient{config: gr.config}).QueryUsers(gr) +} + +// QueryJoinedUsers queries the "joined_users" edge of the Group entity. +func (gr *Group) QueryJoinedUsers() *UserGroupQuery { + return (&GroupClient{config: gr.config}).QueryJoinedUsers(gr) +} + +// Update returns a builder for updating this Group. +// Note that you need to call Group.Unwrap() before calling this method if this Group +// was returned from a transaction, and the transaction was committed or rolled back. +func (gr *Group) Update() *GroupUpdateOne { + return (&GroupClient{config: gr.config}).UpdateOne(gr) +} + +// Unwrap unwraps the Group 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 (gr *Group) Unwrap() *Group { + tx, ok := gr.config.driver.(*txDriver) + if !ok { + panic("ent: Group is not a transactional entity") + } + gr.config.driver = tx.drv + return gr +} + +// String implements the fmt.Stringer. +func (gr *Group) String() string { + var builder strings.Builder + builder.WriteString("Group(") + builder.WriteString(fmt.Sprintf("id=%v, ", gr.ID)) + builder.WriteString("name=") + builder.WriteString(gr.Name) + builder.WriteByte(')') + return builder.String() +} + +// Groups is a parsable slice of Group. +type Groups []*Group + +func (gr Groups) config(cfg config) { + for _i := range gr { + gr[_i].config = cfg + } +} diff --git a/entc/integration/edgeschema/ent/group/group.go b/entc/integration/edgeschema/ent/group/group.go new file mode 100644 index 0000000000..5af3b66741 --- /dev/null +++ b/entc/integration/edgeschema/ent/group/group.go @@ -0,0 +1,57 @@ +// Code generated by entc, DO NOT EDIT. + +package group + +const ( + // Label holds the string label denoting the group type in the database. + Label = "group" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldName holds the string denoting the name field in the database. + FieldName = "name" + // EdgeUsers holds the string denoting the users edge name in mutations. + EdgeUsers = "users" + // EdgeJoinedUsers holds the string denoting the joined_users edge name in mutations. + EdgeJoinedUsers = "joined_users" + // Table holds the table name of the group in the database. + Table = "groups" + // UsersTable is the table that holds the users relation/edge. The primary key declared below. + UsersTable = "user_groups" + // UsersInverseTable is the table name for the User entity. + // It exists in this package in order to avoid circular dependency with the "user" package. + UsersInverseTable = "users" + // JoinedUsersTable is the table that holds the joined_users relation/edge. + JoinedUsersTable = "user_groups" + // JoinedUsersInverseTable is the table name for the UserGroup entity. + // It exists in this package in order to avoid circular dependency with the "usergroup" package. + JoinedUsersInverseTable = "user_groups" + // JoinedUsersColumn is the table column denoting the joined_users relation/edge. + JoinedUsersColumn = "group_id" +) + +// Columns holds all SQL columns for group fields. +var Columns = []string{ + FieldID, + FieldName, +} + +var ( + // UsersPrimaryKey and UsersColumn2 are the table columns denoting the + // primary key for the users relation (M2M). + UsersPrimaryKey = []string{"user_id", "group_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 +} + +var ( + // DefaultName holds the default value on creation for the "name" field. + DefaultName string +) diff --git a/entc/integration/edgeschema/ent/group/where.go b/entc/integration/edgeschema/ent/group/where.go new file mode 100644 index 0000000000..87dcca68be --- /dev/null +++ b/entc/integration/edgeschema/ent/group/where.go @@ -0,0 +1,298 @@ +// Code generated by entc, DO NOT EDIT. + +package group + +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.Group { + return predicate.Group(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.Group { + return predicate.Group(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.Group { + return predicate.Group(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.Group { + return predicate.Group(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.Group { + return predicate.Group(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.Group { + return predicate.Group(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.Group { + return predicate.Group(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.Group { + return predicate.Group(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.Group { + return predicate.Group(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldID), id)) + }) +} + +// Name applies equality check predicate on the "name" field. It's identical to NameEQ. +func Name(v string) predicate.Group { + return predicate.Group(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldName), v)) + }) +} + +// NameEQ applies the EQ predicate on the "name" field. +func NameEQ(v string) predicate.Group { + return predicate.Group(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldName), v)) + }) +} + +// NameNEQ applies the NEQ predicate on the "name" field. +func NameNEQ(v string) predicate.Group { + return predicate.Group(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldName), v)) + }) +} + +// NameIn applies the In predicate on the "name" field. +func NameIn(vs ...string) predicate.Group { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Group(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldName), v...)) + }) +} + +// NameNotIn applies the NotIn predicate on the "name" field. +func NameNotIn(vs ...string) predicate.Group { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Group(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldName), v...)) + }) +} + +// NameGT applies the GT predicate on the "name" field. +func NameGT(v string) predicate.Group { + return predicate.Group(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldName), v)) + }) +} + +// NameGTE applies the GTE predicate on the "name" field. +func NameGTE(v string) predicate.Group { + return predicate.Group(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldName), v)) + }) +} + +// NameLT applies the LT predicate on the "name" field. +func NameLT(v string) predicate.Group { + return predicate.Group(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldName), v)) + }) +} + +// NameLTE applies the LTE predicate on the "name" field. +func NameLTE(v string) predicate.Group { + return predicate.Group(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldName), v)) + }) +} + +// NameContains applies the Contains predicate on the "name" field. +func NameContains(v string) predicate.Group { + return predicate.Group(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldName), v)) + }) +} + +// NameHasPrefix applies the HasPrefix predicate on the "name" field. +func NameHasPrefix(v string) predicate.Group { + return predicate.Group(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldName), v)) + }) +} + +// NameHasSuffix applies the HasSuffix predicate on the "name" field. +func NameHasSuffix(v string) predicate.Group { + return predicate.Group(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldName), v)) + }) +} + +// NameEqualFold applies the EqualFold predicate on the "name" field. +func NameEqualFold(v string) predicate.Group { + return predicate.Group(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldName), v)) + }) +} + +// NameContainsFold applies the ContainsFold predicate on the "name" field. +func NameContainsFold(v string) predicate.Group { + return predicate.Group(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldName), v)) + }) +} + +// HasUsers applies the HasEdge predicate on the "users" edge. +func HasUsers() predicate.Group { + return predicate.Group(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(UsersTable, FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, UsersTable, UsersPrimaryKey...), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasUsersWith applies the HasEdge predicate on the "users" edge with a given conditions (other predicates). +func HasUsersWith(preds ...predicate.User) predicate.Group { + return predicate.Group(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(UsersInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, UsersTable, UsersPrimaryKey...), + ) + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasJoinedUsers applies the HasEdge predicate on the "joined_users" edge. +func HasJoinedUsers() predicate.Group { + return predicate.Group(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(JoinedUsersTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, JoinedUsersTable, JoinedUsersColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasJoinedUsersWith applies the HasEdge predicate on the "joined_users" edge with a given conditions (other predicates). +func HasJoinedUsersWith(preds ...predicate.UserGroup) predicate.Group { + return predicate.Group(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(JoinedUsersInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, JoinedUsersTable, JoinedUsersColumn), + ) + 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.Group) predicate.Group { + return predicate.Group(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.Group) predicate.Group { + return predicate.Group(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.Group) predicate.Group { + return predicate.Group(func(s *sql.Selector) { + p(s.Not()) + }) +} diff --git a/entc/integration/edgeschema/ent/group_create.go b/entc/integration/edgeschema/ent/group_create.go new file mode 100644 index 0000000000..2f6333f3a6 --- /dev/null +++ b/entc/integration/edgeschema/ent/group_create.go @@ -0,0 +1,318 @@ +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/edgeschema/ent/group" + "entgo.io/ent/entc/integration/edgeschema/ent/user" + "entgo.io/ent/entc/integration/edgeschema/ent/usergroup" + "entgo.io/ent/schema/field" +) + +// GroupCreate is the builder for creating a Group entity. +type GroupCreate struct { + config + mutation *GroupMutation + hooks []Hook +} + +// SetName sets the "name" field. +func (gc *GroupCreate) SetName(s string) *GroupCreate { + gc.mutation.SetName(s) + return gc +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (gc *GroupCreate) SetNillableName(s *string) *GroupCreate { + if s != nil { + gc.SetName(*s) + } + return gc +} + +// AddUserIDs adds the "users" edge to the User entity by IDs. +func (gc *GroupCreate) AddUserIDs(ids ...int) *GroupCreate { + gc.mutation.AddUserIDs(ids...) + return gc +} + +// AddUsers adds the "users" edges to the User entity. +func (gc *GroupCreate) AddUsers(u ...*User) *GroupCreate { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return gc.AddUserIDs(ids...) +} + +// AddJoinedUserIDs adds the "joined_users" edge to the UserGroup entity by IDs. +func (gc *GroupCreate) AddJoinedUserIDs(ids ...int) *GroupCreate { + gc.mutation.AddJoinedUserIDs(ids...) + return gc +} + +// AddJoinedUsers adds the "joined_users" edges to the UserGroup entity. +func (gc *GroupCreate) AddJoinedUsers(u ...*UserGroup) *GroupCreate { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return gc.AddJoinedUserIDs(ids...) +} + +// Mutation returns the GroupMutation object of the builder. +func (gc *GroupCreate) Mutation() *GroupMutation { + return gc.mutation +} + +// Save creates the Group in the database. +func (gc *GroupCreate) Save(ctx context.Context) (*Group, error) { + var ( + err error + node *Group + ) + gc.defaults() + if len(gc.hooks) == 0 { + if err = gc.check(); err != nil { + return nil, err + } + node, err = gc.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*GroupMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err = gc.check(); err != nil { + return nil, err + } + gc.mutation = mutation + if node, err = gc.sqlSave(ctx); err != nil { + return nil, err + } + mutation.id = &node.ID + mutation.done = true + return node, err + }) + for i := len(gc.hooks) - 1; i >= 0; i-- { + if gc.hooks[i] == nil { + return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = gc.hooks[i](mut) + } + v, err := mut.Mutate(ctx, gc.mutation) + if err != nil { + return nil, err + } + nv, ok := v.(*Group) + if !ok { + return nil, fmt.Errorf("unexpected node type %T returned from GroupMutation", v) + } + node = nv + } + return node, err +} + +// SaveX calls Save and panics if Save returns an error. +func (gc *GroupCreate) SaveX(ctx context.Context) *Group { + v, err := gc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (gc *GroupCreate) Exec(ctx context.Context) error { + _, err := gc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (gc *GroupCreate) ExecX(ctx context.Context) { + if err := gc.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (gc *GroupCreate) defaults() { + if _, ok := gc.mutation.Name(); !ok { + v := group.DefaultName + gc.mutation.SetName(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (gc *GroupCreate) check() error { + if _, ok := gc.mutation.Name(); !ok { + return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "Group.name"`)} + } + return nil +} + +func (gc *GroupCreate) sqlSave(ctx context.Context) (*Group, error) { + _node, _spec := gc.createSpec() + if err := sqlgraph.CreateNode(ctx, gc.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return nil, err + } + id := _spec.ID.Value.(int64) + _node.ID = int(id) + return _node, nil +} + +func (gc *GroupCreate) createSpec() (*Group, *sqlgraph.CreateSpec) { + var ( + _node = &Group{config: gc.config} + _spec = &sqlgraph.CreateSpec{ + Table: group.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: group.FieldID, + }, + } + ) + if value, ok := gc.mutation.Name(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: group.FieldName, + }) + _node.Name = value + } + if nodes := gc.mutation.UsersIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: group.UsersTable, + Columns: group.UsersPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + createE := &UserGroupCreate{config: gc.config, mutation: newUserGroupMutation(gc.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := gc.mutation.JoinedUsersIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: group.JoinedUsersTable, + Columns: []string{group.JoinedUsersColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: usergroup.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// GroupCreateBulk is the builder for creating many Group entities in bulk. +type GroupCreateBulk struct { + config + builders []*GroupCreate +} + +// Save creates the Group entities in the database. +func (gcb *GroupCreateBulk) Save(ctx context.Context) ([]*Group, error) { + specs := make([]*sqlgraph.CreateSpec, len(gcb.builders)) + nodes := make([]*Group, len(gcb.builders)) + mutators := make([]Mutator, len(gcb.builders)) + for i := range gcb.builders { + func(i int, root context.Context) { + builder := gcb.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*GroupMutation) + 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, gcb.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, gcb.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), 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, gcb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (gcb *GroupCreateBulk) SaveX(ctx context.Context) []*Group { + v, err := gcb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (gcb *GroupCreateBulk) Exec(ctx context.Context) error { + _, err := gcb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (gcb *GroupCreateBulk) ExecX(ctx context.Context) { + if err := gcb.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/entc/integration/edgeschema/ent/group_delete.go b/entc/integration/edgeschema/ent/group_delete.go new file mode 100644 index 0000000000..2e734d9b49 --- /dev/null +++ b/entc/integration/edgeschema/ent/group_delete.go @@ -0,0 +1,111 @@ +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "fmt" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/edgeschema/ent/group" + "entgo.io/ent/entc/integration/edgeschema/ent/predicate" + "entgo.io/ent/schema/field" +) + +// GroupDelete is the builder for deleting a Group entity. +type GroupDelete struct { + config + hooks []Hook + mutation *GroupMutation +} + +// Where appends a list predicates to the GroupDelete builder. +func (gd *GroupDelete) Where(ps ...predicate.Group) *GroupDelete { + gd.mutation.Where(ps...) + return gd +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (gd *GroupDelete) Exec(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(gd.hooks) == 0 { + affected, err = gd.sqlExec(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*GroupMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + gd.mutation = mutation + affected, err = gd.sqlExec(ctx) + mutation.done = true + return affected, err + }) + for i := len(gd.hooks) - 1; i >= 0; i-- { + if gd.hooks[i] == nil { + return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = gd.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, gd.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// ExecX is like Exec, but panics if an error occurs. +func (gd *GroupDelete) ExecX(ctx context.Context) int { + n, err := gd.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (gd *GroupDelete) sqlExec(ctx context.Context) (int, error) { + _spec := &sqlgraph.DeleteSpec{ + Node: &sqlgraph.NodeSpec{ + Table: group.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: group.FieldID, + }, + }, + } + if ps := gd.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return sqlgraph.DeleteNodes(ctx, gd.driver, _spec) +} + +// GroupDeleteOne is the builder for deleting a single Group entity. +type GroupDeleteOne struct { + gd *GroupDelete +} + +// Exec executes the deletion query. +func (gdo *GroupDeleteOne) Exec(ctx context.Context) error { + n, err := gdo.gd.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{group.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (gdo *GroupDeleteOne) ExecX(ctx context.Context) { + gdo.gd.ExecX(ctx) +} diff --git a/entc/integration/edgeschema/ent/group_query.go b/entc/integration/edgeschema/ent/group_query.go new file mode 100644 index 0000000000..b7c6a3112e --- /dev/null +++ b/entc/integration/edgeschema/ent/group_query.go @@ -0,0 +1,686 @@ +// Code generated by entc, 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/group" + "entgo.io/ent/entc/integration/edgeschema/ent/predicate" + "entgo.io/ent/entc/integration/edgeschema/ent/user" + "entgo.io/ent/entc/integration/edgeschema/ent/usergroup" + "entgo.io/ent/schema/field" +) + +// GroupQuery is the builder for querying Group entities. +type GroupQuery struct { + config + limit *int + offset *int + unique *bool + order []OrderFunc + fields []string + predicates []predicate.Group + // eager-loading edges. + withUsers *UserQuery + withJoinedUsers *UserGroupQuery + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the GroupQuery builder. +func (gq *GroupQuery) Where(ps ...predicate.Group) *GroupQuery { + gq.predicates = append(gq.predicates, ps...) + return gq +} + +// Limit adds a limit step to the query. +func (gq *GroupQuery) Limit(limit int) *GroupQuery { + gq.limit = &limit + return gq +} + +// Offset adds an offset step to the query. +func (gq *GroupQuery) Offset(offset int) *GroupQuery { + gq.offset = &offset + return gq +} + +// 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 (gq *GroupQuery) Unique(unique bool) *GroupQuery { + gq.unique = &unique + return gq +} + +// Order adds an order step to the query. +func (gq *GroupQuery) Order(o ...OrderFunc) *GroupQuery { + gq.order = append(gq.order, o...) + return gq +} + +// QueryUsers chains the current query on the "users" edge. +func (gq *GroupQuery) QueryUsers() *UserQuery { + query := &UserQuery{config: gq.config} + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := gq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := gq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(group.Table, group.FieldID, selector), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, group.UsersTable, group.UsersPrimaryKey...), + ) + fromU = sqlgraph.SetNeighbors(gq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryJoinedUsers chains the current query on the "joined_users" edge. +func (gq *GroupQuery) QueryJoinedUsers() *UserGroupQuery { + query := &UserGroupQuery{config: gq.config} + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := gq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := gq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(group.Table, group.FieldID, selector), + sqlgraph.To(usergroup.Table, usergroup.FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, group.JoinedUsersTable, group.JoinedUsersColumn), + ) + fromU = sqlgraph.SetNeighbors(gq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first Group entity from the query. +// Returns a *NotFoundError when no Group was found. +func (gq *GroupQuery) First(ctx context.Context) (*Group, error) { + nodes, err := gq.Limit(1).All(ctx) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{group.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (gq *GroupQuery) FirstX(ctx context.Context) *Group { + node, err := gq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first Group ID from the query. +// Returns a *NotFoundError when no Group ID was found. +func (gq *GroupQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = gq.Limit(1).IDs(ctx); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{group.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (gq *GroupQuery) FirstIDX(ctx context.Context) int { + id, err := gq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single Group entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Group entity is found. +// Returns a *NotFoundError when no Group entities are found. +func (gq *GroupQuery) Only(ctx context.Context) (*Group, error) { + nodes, err := gq.Limit(2).All(ctx) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{group.Label} + default: + return nil, &NotSingularError{group.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (gq *GroupQuery) OnlyX(ctx context.Context) *Group { + node, err := gq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only Group ID in the query. +// Returns a *NotSingularError when more than one Group ID is found. +// Returns a *NotFoundError when no entities are found. +func (gq *GroupQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = gq.Limit(2).IDs(ctx); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{group.Label} + default: + err = &NotSingularError{group.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (gq *GroupQuery) OnlyIDX(ctx context.Context) int { + id, err := gq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of Groups. +func (gq *GroupQuery) All(ctx context.Context) ([]*Group, error) { + if err := gq.prepareQuery(ctx); err != nil { + return nil, err + } + return gq.sqlAll(ctx) +} + +// AllX is like All, but panics if an error occurs. +func (gq *GroupQuery) AllX(ctx context.Context) []*Group { + nodes, err := gq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of Group IDs. +func (gq *GroupQuery) IDs(ctx context.Context) ([]int, error) { + var ids []int + if err := gq.Select(group.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (gq *GroupQuery) IDsX(ctx context.Context) []int { + ids, err := gq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (gq *GroupQuery) Count(ctx context.Context) (int, error) { + if err := gq.prepareQuery(ctx); err != nil { + return 0, err + } + return gq.sqlCount(ctx) +} + +// CountX is like Count, but panics if an error occurs. +func (gq *GroupQuery) CountX(ctx context.Context) int { + count, err := gq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (gq *GroupQuery) Exist(ctx context.Context) (bool, error) { + if err := gq.prepareQuery(ctx); err != nil { + return false, err + } + return gq.sqlExist(ctx) +} + +// ExistX is like Exist, but panics if an error occurs. +func (gq *GroupQuery) ExistX(ctx context.Context) bool { + exist, err := gq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the GroupQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (gq *GroupQuery) Clone() *GroupQuery { + if gq == nil { + return nil + } + return &GroupQuery{ + config: gq.config, + limit: gq.limit, + offset: gq.offset, + order: append([]OrderFunc{}, gq.order...), + predicates: append([]predicate.Group{}, gq.predicates...), + withUsers: gq.withUsers.Clone(), + withJoinedUsers: gq.withJoinedUsers.Clone(), + // clone intermediate query. + sql: gq.sql.Clone(), + path: gq.path, + unique: gq.unique, + } +} + +// WithUsers tells the query-builder to eager-load the nodes that are connected to +// the "users" edge. The optional arguments are used to configure the query builder of the edge. +func (gq *GroupQuery) WithUsers(opts ...func(*UserQuery)) *GroupQuery { + query := &UserQuery{config: gq.config} + for _, opt := range opts { + opt(query) + } + gq.withUsers = query + return gq +} + +// WithJoinedUsers tells the query-builder to eager-load the nodes that are connected to +// the "joined_users" edge. The optional arguments are used to configure the query builder of the edge. +func (gq *GroupQuery) WithJoinedUsers(opts ...func(*UserGroupQuery)) *GroupQuery { + query := &UserGroupQuery{config: gq.config} + for _, opt := range opts { + opt(query) + } + gq.withJoinedUsers = query + return gq +} + +// 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 { +// Name string `json:"name,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.Group.Query(). +// GroupBy(group.FieldName). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +// +func (gq *GroupQuery) GroupBy(field string, fields ...string) *GroupGroupBy { + grbuild := &GroupGroupBy{config: gq.config} + grbuild.fields = append([]string{field}, fields...) + grbuild.path = func(ctx context.Context) (prev *sql.Selector, err error) { + if err := gq.prepareQuery(ctx); err != nil { + return nil, err + } + return gq.sqlQuery(ctx), nil + } + grbuild.label = group.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 { +// Name string `json:"name,omitempty"` +// } +// +// client.Group.Query(). +// Select(group.FieldName). +// Scan(ctx, &v) +// +func (gq *GroupQuery) Select(fields ...string) *GroupSelect { + gq.fields = append(gq.fields, fields...) + selbuild := &GroupSelect{GroupQuery: gq} + selbuild.label = group.Label + selbuild.flds, selbuild.scan = &gq.fields, selbuild.Scan + return selbuild +} + +func (gq *GroupQuery) prepareQuery(ctx context.Context) error { + for _, f := range gq.fields { + if !group.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if gq.path != nil { + prev, err := gq.path(ctx) + if err != nil { + return err + } + gq.sql = prev + } + return nil +} + +func (gq *GroupQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Group, error) { + var ( + nodes = []*Group{} + _spec = gq.querySpec() + loadedTypes = [2]bool{ + gq.withUsers != nil, + gq.withJoinedUsers != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]interface{}, error) { + return (*Group).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []interface{}) error { + node := &Group{config: gq.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, gq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + + if query := gq.withUsers; query != nil { + edgeids := make([]driver.Value, len(nodes)) + byid := make(map[int]*Group) + nids := make(map[int]map[*Group]struct{}) + for i, node := range nodes { + edgeids[i] = node.ID + byid[node.ID] = node + node.Edges.Users = []*User{} + } + query.Where(func(s *sql.Selector) { + joinT := sql.Table(group.UsersTable) + s.Join(joinT).On(s.C(user.FieldID), joinT.C(group.UsersPrimaryKey[0])) + s.Where(sql.InValues(joinT.C(group.UsersPrimaryKey[1]), edgeids...)) + columns := s.SelectedColumns() + s.Select(joinT.C(group.UsersPrimaryKey[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[*Group]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 "users" node returned %v`, n.ID) + } + for kn := range nodes { + kn.Edges.Users = append(kn.Edges.Users, n) + } + } + } + + if query := gq.withJoinedUsers; query != nil { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[int]*Group) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + nodes[i].Edges.JoinedUsers = []*UserGroup{} + } + query.Where(predicate.UserGroup(func(s *sql.Selector) { + s.Where(sql.InValues(group.JoinedUsersColumn, fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return nil, err + } + for _, n := range neighbors { + fk := n.GroupID + node, ok := nodeids[fk] + if !ok { + return nil, fmt.Errorf(`unexpected foreign-key "group_id" returned %v for node %v`, fk, n.ID) + } + node.Edges.JoinedUsers = append(node.Edges.JoinedUsers, n) + } + } + + return nodes, nil +} + +func (gq *GroupQuery) sqlCount(ctx context.Context) (int, error) { + _spec := gq.querySpec() + _spec.Node.Columns = gq.fields + if len(gq.fields) > 0 { + _spec.Unique = gq.unique != nil && *gq.unique + } + return sqlgraph.CountNodes(ctx, gq.driver, _spec) +} + +func (gq *GroupQuery) sqlExist(ctx context.Context) (bool, error) { + n, err := gq.sqlCount(ctx) + if err != nil { + return false, fmt.Errorf("ent: check existence: %w", err) + } + return n > 0, nil +} + +func (gq *GroupQuery) querySpec() *sqlgraph.QuerySpec { + _spec := &sqlgraph.QuerySpec{ + Node: &sqlgraph.NodeSpec{ + Table: group.Table, + Columns: group.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: group.FieldID, + }, + }, + From: gq.sql, + Unique: true, + } + if unique := gq.unique; unique != nil { + _spec.Unique = *unique + } + if fields := gq.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, group.FieldID) + for i := range fields { + if fields[i] != group.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := gq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := gq.limit; limit != nil { + _spec.Limit = *limit + } + if offset := gq.offset; offset != nil { + _spec.Offset = *offset + } + if ps := gq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (gq *GroupQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(gq.driver.Dialect()) + t1 := builder.Table(group.Table) + columns := gq.fields + if len(columns) == 0 { + columns = group.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if gq.sql != nil { + selector = gq.sql + selector.Select(selector.Columns(columns...)...) + } + if gq.unique != nil && *gq.unique { + selector.Distinct() + } + for _, p := range gq.predicates { + p(selector) + } + for _, p := range gq.order { + p(selector) + } + if offset := gq.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 := gq.limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// GroupGroupBy is the group-by builder for Group entities. +type GroupGroupBy 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 (ggb *GroupGroupBy) Aggregate(fns ...AggregateFunc) *GroupGroupBy { + ggb.fns = append(ggb.fns, fns...) + return ggb +} + +// Scan applies the group-by query and scans the result into the given value. +func (ggb *GroupGroupBy) Scan(ctx context.Context, v interface{}) error { + query, err := ggb.path(ctx) + if err != nil { + return err + } + ggb.sql = query + return ggb.sqlScan(ctx, v) +} + +func (ggb *GroupGroupBy) sqlScan(ctx context.Context, v interface{}) error { + for _, f := range ggb.fields { + if !group.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)} + } + } + selector := ggb.sqlQuery() + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := ggb.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +func (ggb *GroupGroupBy) sqlQuery() *sql.Selector { + selector := ggb.sql.Select() + aggregation := make([]string, 0, len(ggb.fns)) + for _, fn := range ggb.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(ggb.fields)+len(ggb.fns)) + for _, f := range ggb.fields { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + return selector.GroupBy(selector.Columns(ggb.fields...)...) +} + +// GroupSelect is the builder for selecting fields of Group entities. +type GroupSelect struct { + *GroupQuery + selector + // intermediate query (i.e. traversal path). + sql *sql.Selector +} + +// Scan applies the selector query and scans the result into the given value. +func (gs *GroupSelect) Scan(ctx context.Context, v interface{}) error { + if err := gs.prepareQuery(ctx); err != nil { + return err + } + gs.sql = gs.GroupQuery.sqlQuery(ctx) + return gs.sqlScan(ctx, v) +} + +func (gs *GroupSelect) sqlScan(ctx context.Context, v interface{}) error { + rows := &sql.Rows{} + query, args := gs.sql.Query() + if err := gs.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/group_update.go b/entc/integration/edgeschema/ent/group_update.go new file mode 100644 index 0000000000..804052b37f --- /dev/null +++ b/entc/integration/edgeschema/ent/group_update.go @@ -0,0 +1,673 @@ +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/edgeschema/ent/group" + "entgo.io/ent/entc/integration/edgeschema/ent/predicate" + "entgo.io/ent/entc/integration/edgeschema/ent/user" + "entgo.io/ent/entc/integration/edgeschema/ent/usergroup" + "entgo.io/ent/schema/field" +) + +// GroupUpdate is the builder for updating Group entities. +type GroupUpdate struct { + config + hooks []Hook + mutation *GroupMutation +} + +// Where appends a list predicates to the GroupUpdate builder. +func (gu *GroupUpdate) Where(ps ...predicate.Group) *GroupUpdate { + gu.mutation.Where(ps...) + return gu +} + +// SetName sets the "name" field. +func (gu *GroupUpdate) SetName(s string) *GroupUpdate { + gu.mutation.SetName(s) + return gu +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (gu *GroupUpdate) SetNillableName(s *string) *GroupUpdate { + if s != nil { + gu.SetName(*s) + } + return gu +} + +// AddUserIDs adds the "users" edge to the User entity by IDs. +func (gu *GroupUpdate) AddUserIDs(ids ...int) *GroupUpdate { + gu.mutation.AddUserIDs(ids...) + return gu +} + +// AddUsers adds the "users" edges to the User entity. +func (gu *GroupUpdate) AddUsers(u ...*User) *GroupUpdate { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return gu.AddUserIDs(ids...) +} + +// AddJoinedUserIDs adds the "joined_users" edge to the UserGroup entity by IDs. +func (gu *GroupUpdate) AddJoinedUserIDs(ids ...int) *GroupUpdate { + gu.mutation.AddJoinedUserIDs(ids...) + return gu +} + +// AddJoinedUsers adds the "joined_users" edges to the UserGroup entity. +func (gu *GroupUpdate) AddJoinedUsers(u ...*UserGroup) *GroupUpdate { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return gu.AddJoinedUserIDs(ids...) +} + +// Mutation returns the GroupMutation object of the builder. +func (gu *GroupUpdate) Mutation() *GroupMutation { + return gu.mutation +} + +// ClearUsers clears all "users" edges to the User entity. +func (gu *GroupUpdate) ClearUsers() *GroupUpdate { + gu.mutation.ClearUsers() + return gu +} + +// RemoveUserIDs removes the "users" edge to User entities by IDs. +func (gu *GroupUpdate) RemoveUserIDs(ids ...int) *GroupUpdate { + gu.mutation.RemoveUserIDs(ids...) + return gu +} + +// RemoveUsers removes "users" edges to User entities. +func (gu *GroupUpdate) RemoveUsers(u ...*User) *GroupUpdate { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return gu.RemoveUserIDs(ids...) +} + +// ClearJoinedUsers clears all "joined_users" edges to the UserGroup entity. +func (gu *GroupUpdate) ClearJoinedUsers() *GroupUpdate { + gu.mutation.ClearJoinedUsers() + return gu +} + +// RemoveJoinedUserIDs removes the "joined_users" edge to UserGroup entities by IDs. +func (gu *GroupUpdate) RemoveJoinedUserIDs(ids ...int) *GroupUpdate { + gu.mutation.RemoveJoinedUserIDs(ids...) + return gu +} + +// RemoveJoinedUsers removes "joined_users" edges to UserGroup entities. +func (gu *GroupUpdate) RemoveJoinedUsers(u ...*UserGroup) *GroupUpdate { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return gu.RemoveJoinedUserIDs(ids...) +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (gu *GroupUpdate) Save(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(gu.hooks) == 0 { + affected, err = gu.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*GroupMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + gu.mutation = mutation + affected, err = gu.sqlSave(ctx) + mutation.done = true + return affected, err + }) + for i := len(gu.hooks) - 1; i >= 0; i-- { + if gu.hooks[i] == nil { + return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = gu.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, gu.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// SaveX is like Save, but panics if an error occurs. +func (gu *GroupUpdate) SaveX(ctx context.Context) int { + affected, err := gu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (gu *GroupUpdate) Exec(ctx context.Context) error { + _, err := gu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (gu *GroupUpdate) ExecX(ctx context.Context) { + if err := gu.Exec(ctx); err != nil { + panic(err) + } +} + +func (gu *GroupUpdate) sqlSave(ctx context.Context) (n int, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: group.Table, + Columns: group.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: group.FieldID, + }, + }, + } + if ps := gu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := gu.mutation.Name(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: group.FieldName, + }) + } + if gu.mutation.UsersCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: group.UsersTable, + Columns: group.UsersPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + createE := &UserGroupCreate{config: gu.config, mutation: newUserGroupMutation(gu.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := gu.mutation.RemovedUsersIDs(); len(nodes) > 0 && !gu.mutation.UsersCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: group.UsersTable, + Columns: group.UsersPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + createE := &UserGroupCreate{config: gu.config, mutation: newUserGroupMutation(gu.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := gu.mutation.UsersIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: group.UsersTable, + Columns: group.UsersPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + createE := &UserGroupCreate{config: gu.config, mutation: newUserGroupMutation(gu.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if gu.mutation.JoinedUsersCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: group.JoinedUsersTable, + Columns: []string{group.JoinedUsersColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: usergroup.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := gu.mutation.RemovedJoinedUsersIDs(); len(nodes) > 0 && !gu.mutation.JoinedUsersCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: group.JoinedUsersTable, + Columns: []string{group.JoinedUsersColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: usergroup.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := gu.mutation.JoinedUsersIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: group.JoinedUsersTable, + Columns: []string{group.JoinedUsersColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: usergroup.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, gu.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{group.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return 0, err + } + return n, nil +} + +// GroupUpdateOne is the builder for updating a single Group entity. +type GroupUpdateOne struct { + config + fields []string + hooks []Hook + mutation *GroupMutation +} + +// SetName sets the "name" field. +func (guo *GroupUpdateOne) SetName(s string) *GroupUpdateOne { + guo.mutation.SetName(s) + return guo +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (guo *GroupUpdateOne) SetNillableName(s *string) *GroupUpdateOne { + if s != nil { + guo.SetName(*s) + } + return guo +} + +// AddUserIDs adds the "users" edge to the User entity by IDs. +func (guo *GroupUpdateOne) AddUserIDs(ids ...int) *GroupUpdateOne { + guo.mutation.AddUserIDs(ids...) + return guo +} + +// AddUsers adds the "users" edges to the User entity. +func (guo *GroupUpdateOne) AddUsers(u ...*User) *GroupUpdateOne { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return guo.AddUserIDs(ids...) +} + +// AddJoinedUserIDs adds the "joined_users" edge to the UserGroup entity by IDs. +func (guo *GroupUpdateOne) AddJoinedUserIDs(ids ...int) *GroupUpdateOne { + guo.mutation.AddJoinedUserIDs(ids...) + return guo +} + +// AddJoinedUsers adds the "joined_users" edges to the UserGroup entity. +func (guo *GroupUpdateOne) AddJoinedUsers(u ...*UserGroup) *GroupUpdateOne { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return guo.AddJoinedUserIDs(ids...) +} + +// Mutation returns the GroupMutation object of the builder. +func (guo *GroupUpdateOne) Mutation() *GroupMutation { + return guo.mutation +} + +// ClearUsers clears all "users" edges to the User entity. +func (guo *GroupUpdateOne) ClearUsers() *GroupUpdateOne { + guo.mutation.ClearUsers() + return guo +} + +// RemoveUserIDs removes the "users" edge to User entities by IDs. +func (guo *GroupUpdateOne) RemoveUserIDs(ids ...int) *GroupUpdateOne { + guo.mutation.RemoveUserIDs(ids...) + return guo +} + +// RemoveUsers removes "users" edges to User entities. +func (guo *GroupUpdateOne) RemoveUsers(u ...*User) *GroupUpdateOne { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return guo.RemoveUserIDs(ids...) +} + +// ClearJoinedUsers clears all "joined_users" edges to the UserGroup entity. +func (guo *GroupUpdateOne) ClearJoinedUsers() *GroupUpdateOne { + guo.mutation.ClearJoinedUsers() + return guo +} + +// RemoveJoinedUserIDs removes the "joined_users" edge to UserGroup entities by IDs. +func (guo *GroupUpdateOne) RemoveJoinedUserIDs(ids ...int) *GroupUpdateOne { + guo.mutation.RemoveJoinedUserIDs(ids...) + return guo +} + +// RemoveJoinedUsers removes "joined_users" edges to UserGroup entities. +func (guo *GroupUpdateOne) RemoveJoinedUsers(u ...*UserGroup) *GroupUpdateOne { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return guo.RemoveJoinedUserIDs(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 (guo *GroupUpdateOne) Select(field string, fields ...string) *GroupUpdateOne { + guo.fields = append([]string{field}, fields...) + return guo +} + +// Save executes the query and returns the updated Group entity. +func (guo *GroupUpdateOne) Save(ctx context.Context) (*Group, error) { + var ( + err error + node *Group + ) + if len(guo.hooks) == 0 { + node, err = guo.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*GroupMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + guo.mutation = mutation + node, err = guo.sqlSave(ctx) + mutation.done = true + return node, err + }) + for i := len(guo.hooks) - 1; i >= 0; i-- { + if guo.hooks[i] == nil { + return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = guo.hooks[i](mut) + } + v, err := mut.Mutate(ctx, guo.mutation) + if err != nil { + return nil, err + } + nv, ok := v.(*Group) + if !ok { + return nil, fmt.Errorf("unexpected node type %T returned from GroupMutation", v) + } + node = nv + } + return node, err +} + +// SaveX is like Save, but panics if an error occurs. +func (guo *GroupUpdateOne) SaveX(ctx context.Context) *Group { + node, err := guo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (guo *GroupUpdateOne) Exec(ctx context.Context) error { + _, err := guo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (guo *GroupUpdateOne) ExecX(ctx context.Context) { + if err := guo.Exec(ctx); err != nil { + panic(err) + } +} + +func (guo *GroupUpdateOne) sqlSave(ctx context.Context) (_node *Group, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: group.Table, + Columns: group.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: group.FieldID, + }, + }, + } + id, ok := guo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Group.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := guo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, group.FieldID) + for _, f := range fields { + if !group.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != group.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := guo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := guo.mutation.Name(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: group.FieldName, + }) + } + if guo.mutation.UsersCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: group.UsersTable, + Columns: group.UsersPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + createE := &UserGroupCreate{config: guo.config, mutation: newUserGroupMutation(guo.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := guo.mutation.RemovedUsersIDs(); len(nodes) > 0 && !guo.mutation.UsersCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: group.UsersTable, + Columns: group.UsersPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + createE := &UserGroupCreate{config: guo.config, mutation: newUserGroupMutation(guo.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := guo.mutation.UsersIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: group.UsersTable, + Columns: group.UsersPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + createE := &UserGroupCreate{config: guo.config, mutation: newUserGroupMutation(guo.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if guo.mutation.JoinedUsersCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: group.JoinedUsersTable, + Columns: []string{group.JoinedUsersColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: usergroup.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := guo.mutation.RemovedJoinedUsersIDs(); len(nodes) > 0 && !guo.mutation.JoinedUsersCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: group.JoinedUsersTable, + Columns: []string{group.JoinedUsersColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: usergroup.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := guo.mutation.JoinedUsersIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: group.JoinedUsersTable, + Columns: []string{group.JoinedUsersColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: usergroup.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &Group{config: guo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, guo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{group.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return nil, err + } + return _node, nil +} diff --git a/entc/integration/edgeschema/ent/hook/hook.go b/entc/integration/edgeschema/ent/hook/hook.go new file mode 100644 index 0000000000..7b69cce5c7 --- /dev/null +++ b/entc/integration/edgeschema/ent/hook/hook.go @@ -0,0 +1,282 @@ +// Code generated by entc, DO NOT EDIT. + +package hook + +import ( + "context" + "fmt" + + "entgo.io/ent/entc/integration/edgeschema/ent" +) + +// The FriendshipFunc type is an adapter to allow the use of ordinary +// function as Friendship mutator. +type FriendshipFunc func(context.Context, *ent.FriendshipMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f FriendshipFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + mv, ok := m.(*ent.FriendshipMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.FriendshipMutation", m) + } + return f(ctx, mv) +} + +// The GroupFunc type is an adapter to allow the use of ordinary +// function as Group mutator. +type GroupFunc func(context.Context, *ent.GroupMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f GroupFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + mv, ok := m.(*ent.GroupMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.GroupMutation", m) + } + return f(ctx, mv) +} + +// The RelationshipFunc type is an adapter to allow the use of ordinary +// function as Relationship mutator. +type RelationshipFunc func(context.Context, *ent.RelationshipMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f RelationshipFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + mv, ok := m.(*ent.RelationshipMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.RelationshipMutation", 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) + +// Mutate calls f(ctx, m). +func (f TweetFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + mv, ok := m.(*ent.TweetMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.TweetMutation", m) + } + return f(ctx, mv) +} + +// The TweetLikeFunc type is an adapter to allow the use of ordinary +// function as TweetLike mutator. +type TweetLikeFunc func(context.Context, *ent.TweetLikeMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f TweetLikeFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + mv, ok := m.(*ent.TweetLikeMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.TweetLikeMutation", 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) + +// Mutate calls f(ctx, m). +func (f UserFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + mv, ok := m.(*ent.UserMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.UserMutation", m) + } + return f(ctx, mv) +} + +// The UserGroupFunc type is an adapter to allow the use of ordinary +// function as UserGroup mutator. +type UserGroupFunc func(context.Context, *ent.UserGroupMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f UserGroupFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + mv, ok := m.(*ent.UserGroupMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.UserGroupMutation", m) + } + return f(ctx, mv) +} + +// Condition is a hook condition function. +type Condition func(context.Context, ent.Mutation) bool + +// And groups conditions with the AND operator. +func And(first, second Condition, rest ...Condition) Condition { + return func(ctx context.Context, m ent.Mutation) bool { + if !first(ctx, m) || !second(ctx, m) { + return false + } + for _, cond := range rest { + if !cond(ctx, m) { + return false + } + } + return true + } +} + +// Or groups conditions with the OR operator. +func Or(first, second Condition, rest ...Condition) Condition { + return func(ctx context.Context, m ent.Mutation) bool { + if first(ctx, m) || second(ctx, m) { + return true + } + for _, cond := range rest { + if cond(ctx, m) { + return true + } + } + return false + } +} + +// Not negates a given condition. +func Not(cond Condition) Condition { + return func(ctx context.Context, m ent.Mutation) bool { + return !cond(ctx, m) + } +} + +// HasOp is a condition testing mutation operation. +func HasOp(op ent.Op) Condition { + return func(_ context.Context, m ent.Mutation) bool { + return m.Op().Is(op) + } +} + +// HasAddedFields is a condition validating `.AddedField` on fields. +func HasAddedFields(field string, fields ...string) Condition { + return func(_ context.Context, m ent.Mutation) bool { + if _, exists := m.AddedField(field); !exists { + return false + } + for _, field := range fields { + if _, exists := m.AddedField(field); !exists { + return false + } + } + return true + } +} + +// HasClearedFields is a condition validating `.FieldCleared` on fields. +func HasClearedFields(field string, fields ...string) Condition { + return func(_ context.Context, m ent.Mutation) bool { + if exists := m.FieldCleared(field); !exists { + return false + } + for _, field := range fields { + if exists := m.FieldCleared(field); !exists { + return false + } + } + return true + } +} + +// HasFields is a condition validating `.Field` on fields. +func HasFields(field string, fields ...string) Condition { + return func(_ context.Context, m ent.Mutation) bool { + if _, exists := m.Field(field); !exists { + return false + } + for _, field := range fields { + if _, exists := m.Field(field); !exists { + return false + } + } + return true + } +} + +// If executes the given hook under condition. +// +// hook.If(ComputeAverage, And(HasFields(...), HasAddedFields(...))) +// +func If(hk ent.Hook, cond Condition) ent.Hook { + return func(next ent.Mutator) ent.Mutator { + return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if cond(ctx, m) { + return hk(next).Mutate(ctx, m) + } + return next.Mutate(ctx, m) + }) + } +} + +// On executes the given hook only for the given operation. +// +// hook.On(Log, ent.Delete|ent.Create) +// +func On(hk ent.Hook, op ent.Op) ent.Hook { + return If(hk, HasOp(op)) +} + +// Unless skips the given hook only for the given operation. +// +// hook.Unless(Log, ent.Update|ent.UpdateOne) +// +func Unless(hk ent.Hook, op ent.Op) ent.Hook { + return If(hk, Not(HasOp(op))) +} + +// FixedError is a hook returning a fixed error. +func FixedError(err error) ent.Hook { + return func(ent.Mutator) ent.Mutator { + return ent.MutateFunc(func(context.Context, ent.Mutation) (ent.Value, error) { + return nil, err + }) + } +} + +// Reject returns a hook that rejects all operations that match op. +// +// func (T) Hooks() []ent.Hook { +// return []ent.Hook{ +// Reject(ent.Delete|ent.Update), +// } +// } +// +func Reject(op ent.Op) ent.Hook { + hk := FixedError(fmt.Errorf("%s operation is not allowed", op)) + return On(hk, op) +} + +// Chain acts as a list of hooks and is effectively immutable. +// Once created, it will always hold the same set of hooks in the same order. +type Chain struct { + hooks []ent.Hook +} + +// NewChain creates a new chain of hooks. +func NewChain(hooks ...ent.Hook) Chain { + return Chain{append([]ent.Hook(nil), hooks...)} +} + +// Hook chains the list of hooks and returns the final hook. +func (c Chain) Hook() ent.Hook { + return func(mutator ent.Mutator) ent.Mutator { + for i := len(c.hooks) - 1; i >= 0; i-- { + mutator = c.hooks[i](mutator) + } + return mutator + } +} + +// Append extends a chain, adding the specified hook +// as the last ones in the mutation flow. +func (c Chain) Append(hooks ...ent.Hook) Chain { + newHooks := make([]ent.Hook, 0, len(c.hooks)+len(hooks)) + newHooks = append(newHooks, c.hooks...) + newHooks = append(newHooks, hooks...) + return Chain{newHooks} +} + +// Extend extends a chain, adding the specified chain +// as the last ones in the mutation flow. +func (c Chain) Extend(chain Chain) Chain { + return c.Append(chain.hooks...) +} diff --git a/entc/integration/edgeschema/ent/migrate/migrate.go b/entc/integration/edgeschema/ent/migrate/migrate.go new file mode 100644 index 0000000000..9bdaf52377 --- /dev/null +++ b/entc/integration/edgeschema/ent/migrate/migrate.go @@ -0,0 +1,71 @@ +// Code generated by entc, DO NOT EDIT. + +package migrate + +import ( + "context" + "fmt" + "io" + + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql/schema" +) + +var ( + // WithGlobalUniqueID sets the universal ids options to the migration. + // If this option is enabled, ent migration will allocate a 1<<32 range + // for the ids of each entity (table). + // Note that this option cannot be applied on tables that already exist. + WithGlobalUniqueID = schema.WithGlobalUniqueID + // WithDropColumn sets the drop column option to the migration. + // If this option is enabled, ent migration will drop old columns + // that were used for both fields and edges. This defaults to false. + WithDropColumn = schema.WithDropColumn + // WithDropIndex sets the drop index option to the migration. + // If this option is enabled, ent migration will drop old indexes + // that were defined in the schema. This defaults to false. + // Note that unique constraints are defined using `UNIQUE INDEX`, + // and therefore, it's recommended to enable this option to get more + // flexibility in the schema changes. + WithDropIndex = schema.WithDropIndex + // WithFixture sets the foreign-key renaming option to the migration when upgrading + // ent from v0.1.0 (issue-#285). Defaults to false. + WithFixture = schema.WithFixture + // WithForeignKeys enables creating foreign-key in schema DDL. This defaults to true. + WithForeignKeys = schema.WithForeignKeys +) + +// Schema is the API for creating, migrating and dropping a schema. +type Schema struct { + drv dialect.Driver +} + +// NewSchema creates a new schema client. +func NewSchema(drv dialect.Driver) *Schema { return &Schema{drv: drv} } + +// Create creates all schema resources. +func (s *Schema) Create(ctx context.Context, opts ...schema.MigrateOption) error { + migrate, err := schema.NewMigrate(s.drv, opts...) + if err != nil { + return fmt.Errorf("ent/migrate: %w", err) + } + return migrate.Create(ctx, Tables...) +} + +// WriteTo writes the schema changes to w instead of running them against the database. +// +// if err := client.Schema.WriteTo(context.Background(), os.Stdout); err != nil { +// log.Fatal(err) +// } +// +func (s *Schema) WriteTo(ctx context.Context, w io.Writer, opts ...schema.MigrateOption) error { + drv := &schema.WriteDriver{ + Writer: w, + Driver: s.drv, + } + migrate, err := schema.NewMigrate(drv, opts...) + if err != nil { + return fmt.Errorf("ent/migrate: %w", err) + } + return migrate.Create(ctx, Tables...) +} diff --git a/entc/integration/edgeschema/ent/migrate/schema.go b/entc/integration/edgeschema/ent/migrate/schema.go new file mode 100644 index 0000000000..f9a9563057 --- /dev/null +++ b/entc/integration/edgeschema/ent/migrate/schema.go @@ -0,0 +1,186 @@ +// Code generated by entc, DO NOT EDIT. + +package migrate + +import ( + "entgo.io/ent/dialect/sql/schema" + "entgo.io/ent/schema/field" +) + +var ( + // FriendshipsColumns holds the columns for the "friendships" table. + FriendshipsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "weight", Type: field.TypeInt, Default: 1}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "user_id", Type: field.TypeInt}, + {Name: "friend_id", Type: field.TypeInt}, + } + // FriendshipsTable holds the schema information for the "friendships" table. + FriendshipsTable = &schema.Table{ + Name: "friendships", + Columns: FriendshipsColumns, + PrimaryKey: []*schema.Column{FriendshipsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "friendships_users_user", + Columns: []*schema.Column{FriendshipsColumns[3]}, + RefColumns: []*schema.Column{UsersColumns[0]}, + OnDelete: schema.NoAction, + }, + { + Symbol: "friendships_users_friend", + Columns: []*schema.Column{FriendshipsColumns[4]}, + RefColumns: []*schema.Column{UsersColumns[0]}, + OnDelete: schema.NoAction, + }, + }, + Indexes: []*schema.Index{ + { + Name: "friendship_user_id_friend_id", + Unique: true, + Columns: []*schema.Column{FriendshipsColumns[3], FriendshipsColumns[4]}, + }, + }, + } + // GroupsColumns holds the columns for the "groups" table. + GroupsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "name", Type: field.TypeString, Default: "Unknown"}, + } + // GroupsTable holds the schema information for the "groups" table. + GroupsTable = &schema.Table{ + Name: "groups", + Columns: GroupsColumns, + PrimaryKey: []*schema.Column{GroupsColumns[0]}, + } + // RelationshipsColumns holds the columns for the "relationships" table. + RelationshipsColumns = []*schema.Column{ + {Name: "weight", Type: field.TypeInt, Default: 1}, + {Name: "user_id", Type: field.TypeInt}, + {Name: "relative_id", Type: field.TypeInt}, + } + // RelationshipsTable holds the schema information for the "relationships" table. + RelationshipsTable = &schema.Table{ + Name: "relationships", + Columns: RelationshipsColumns, + PrimaryKey: []*schema.Column{RelationshipsColumns[1], RelationshipsColumns[2]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "relationships_users_user", + Columns: []*schema.Column{RelationshipsColumns[1]}, + RefColumns: []*schema.Column{UsersColumns[0]}, + OnDelete: schema.NoAction, + }, + { + Symbol: "relationships_users_relative", + Columns: []*schema.Column{RelationshipsColumns[2]}, + RefColumns: []*schema.Column{UsersColumns[0]}, + OnDelete: schema.NoAction, + }, + }, + } + // TweetsColumns holds the columns for the "tweets" table. + TweetsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "text", Type: field.TypeString, Size: 2147483647}, + } + // TweetsTable holds the schema information for the "tweets" table. + TweetsTable = &schema.Table{ + Name: "tweets", + Columns: TweetsColumns, + PrimaryKey: []*schema.Column{TweetsColumns[0]}, + } + // TweetLikesColumns holds the columns for the "tweet_likes" table. + TweetLikesColumns = []*schema.Column{ + {Name: "liked_at", Type: field.TypeTime}, + {Name: "user_id", Type: field.TypeInt}, + {Name: "tweet_id", Type: field.TypeInt}, + } + // TweetLikesTable holds the schema information for the "tweet_likes" table. + TweetLikesTable = &schema.Table{ + Name: "tweet_likes", + Columns: TweetLikesColumns, + PrimaryKey: []*schema.Column{TweetLikesColumns[1], TweetLikesColumns[2]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "tweet_likes_users_user", + Columns: []*schema.Column{TweetLikesColumns[1]}, + RefColumns: []*schema.Column{UsersColumns[0]}, + OnDelete: schema.NoAction, + }, + { + Symbol: "tweet_likes_tweets_tweet", + Columns: []*schema.Column{TweetLikesColumns[2]}, + RefColumns: []*schema.Column{TweetsColumns[0]}, + OnDelete: schema.NoAction, + }, + }, + } + // UsersColumns holds the columns for the "users" table. + UsersColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "name", Type: field.TypeString, Default: "Unknown"}, + } + // UsersTable holds the schema information for the "users" table. + UsersTable = &schema.Table{ + Name: "users", + Columns: UsersColumns, + PrimaryKey: []*schema.Column{UsersColumns[0]}, + } + // UserGroupsColumns holds the columns for the "user_groups" table. + UserGroupsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "joined_at", Type: field.TypeTime}, + {Name: "user_id", Type: field.TypeInt}, + {Name: "group_id", Type: field.TypeInt}, + } + // UserGroupsTable holds the schema information for the "user_groups" table. + UserGroupsTable = &schema.Table{ + Name: "user_groups", + Columns: UserGroupsColumns, + PrimaryKey: []*schema.Column{UserGroupsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "user_groups_users_user", + Columns: []*schema.Column{UserGroupsColumns[2]}, + RefColumns: []*schema.Column{UsersColumns[0]}, + OnDelete: schema.NoAction, + }, + { + Symbol: "user_groups_groups_group", + Columns: []*schema.Column{UserGroupsColumns[3]}, + RefColumns: []*schema.Column{GroupsColumns[0]}, + OnDelete: schema.NoAction, + }, + }, + Indexes: []*schema.Index{ + { + Name: "usergroup_user_id_group_id", + Unique: true, + Columns: []*schema.Column{UserGroupsColumns[2], UserGroupsColumns[3]}, + }, + }, + } + // Tables holds all the tables in the schema. + Tables = []*schema.Table{ + FriendshipsTable, + GroupsTable, + RelationshipsTable, + TweetsTable, + TweetLikesTable, + UsersTable, + UserGroupsTable, + } +) + +func init() { + FriendshipsTable.ForeignKeys[0].RefTable = UsersTable + FriendshipsTable.ForeignKeys[1].RefTable = UsersTable + RelationshipsTable.ForeignKeys[0].RefTable = UsersTable + RelationshipsTable.ForeignKeys[1].RefTable = UsersTable + TweetLikesTable.ForeignKeys[0].RefTable = UsersTable + TweetLikesTable.ForeignKeys[1].RefTable = TweetsTable + UserGroupsTable.ForeignKeys[0].RefTable = UsersTable + UserGroupsTable.ForeignKeys[1].RefTable = GroupsTable +} diff --git a/entc/integration/edgeschema/ent/mutation.go b/entc/integration/edgeschema/ent/mutation.go new file mode 100644 index 0000000000..0ee59dd7bc --- /dev/null +++ b/entc/integration/edgeschema/ent/mutation.go @@ -0,0 +1,3718 @@ +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "sync" + "time" + + "entgo.io/ent/entc/integration/edgeschema/ent/friendship" + "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/tweet" + "entgo.io/ent/entc/integration/edgeschema/ent/tweetlike" + "entgo.io/ent/entc/integration/edgeschema/ent/user" + "entgo.io/ent/entc/integration/edgeschema/ent/usergroup" + + "entgo.io/ent" +) + +const ( + // Operation types. + OpCreate = ent.OpCreate + OpDelete = ent.OpDelete + OpDeleteOne = ent.OpDeleteOne + OpUpdate = ent.OpUpdate + OpUpdateOne = ent.OpUpdateOne + + // Node types. + TypeFriendship = "Friendship" + TypeGroup = "Group" + TypeRelationship = "Relationship" + TypeTweet = "Tweet" + TypeTweetLike = "TweetLike" + TypeUser = "User" + TypeUserGroup = "UserGroup" +) + +// FriendshipMutation represents an operation that mutates the Friendship nodes in the graph. +type FriendshipMutation struct { + config + op Op + typ string + id *int + weight *int + addweight *int + created_at *time.Time + clearedFields map[string]struct{} + user *int + cleareduser bool + friend *int + clearedfriend bool + done bool + oldValue func(context.Context) (*Friendship, error) + predicates []predicate.Friendship +} + +var _ ent.Mutation = (*FriendshipMutation)(nil) + +// friendshipOption allows management of the mutation configuration using functional options. +type friendshipOption func(*FriendshipMutation) + +// newFriendshipMutation creates new mutation for the Friendship entity. +func newFriendshipMutation(c config, op Op, opts ...friendshipOption) *FriendshipMutation { + m := &FriendshipMutation{ + config: c, + op: op, + typ: TypeFriendship, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withFriendshipID sets the ID field of the mutation. +func withFriendshipID(id int) friendshipOption { + return func(m *FriendshipMutation) { + var ( + err error + once sync.Once + value *Friendship + ) + m.oldValue = func(ctx context.Context) (*Friendship, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Friendship.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withFriendship sets the old Friendship of the mutation. +func withFriendship(node *Friendship) friendshipOption { + return func(m *FriendshipMutation) { + m.oldValue = func(context.Context) (*Friendship, 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 FriendshipMutation) 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 FriendshipMutation) 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 *FriendshipMutation) 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 *FriendshipMutation) 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().Friendship.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetWeight sets the "weight" field. +func (m *FriendshipMutation) SetWeight(i int) { + m.weight = &i + m.addweight = nil +} + +// Weight returns the value of the "weight" field in the mutation. +func (m *FriendshipMutation) Weight() (r int, exists bool) { + v := m.weight + if v == nil { + return + } + return *v, true +} + +// OldWeight returns the old "weight" field's value of the Friendship entity. +// If the Friendship 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 *FriendshipMutation) OldWeight(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldWeight is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldWeight requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldWeight: %w", err) + } + return oldValue.Weight, nil +} + +// AddWeight adds i to the "weight" field. +func (m *FriendshipMutation) AddWeight(i int) { + if m.addweight != nil { + *m.addweight += i + } else { + m.addweight = &i + } +} + +// AddedWeight returns the value that was added to the "weight" field in this mutation. +func (m *FriendshipMutation) AddedWeight() (r int, exists bool) { + v := m.addweight + if v == nil { + return + } + return *v, true +} + +// ResetWeight resets all changes to the "weight" field. +func (m *FriendshipMutation) ResetWeight() { + m.weight = nil + m.addweight = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *FriendshipMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *FriendshipMutation) CreatedAt() (r time.Time, exists bool) { + v := m.created_at + if v == nil { + return + } + return *v, true +} + +// OldCreatedAt returns the old "created_at" field's value of the Friendship entity. +// If the Friendship 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 *FriendshipMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCreatedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) + } + return oldValue.CreatedAt, nil +} + +// ResetCreatedAt resets all changes to the "created_at" field. +func (m *FriendshipMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUserID sets the "user_id" field. +func (m *FriendshipMutation) SetUserID(i int) { + m.user = &i +} + +// UserID returns the value of the "user_id" field in the mutation. +func (m *FriendshipMutation) UserID() (r int, exists bool) { + v := m.user + if v == nil { + return + } + return *v, true +} + +// OldUserID returns the old "user_id" field's value of the Friendship entity. +// If the Friendship 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 *FriendshipMutation) OldUserID(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUserID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUserID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUserID: %w", err) + } + return oldValue.UserID, nil +} + +// ResetUserID resets all changes to the "user_id" field. +func (m *FriendshipMutation) ResetUserID() { + m.user = nil +} + +// SetFriendID sets the "friend_id" field. +func (m *FriendshipMutation) SetFriendID(i int) { + m.friend = &i +} + +// FriendID returns the value of the "friend_id" field in the mutation. +func (m *FriendshipMutation) FriendID() (r int, exists bool) { + v := m.friend + if v == nil { + return + } + return *v, true +} + +// OldFriendID returns the old "friend_id" field's value of the Friendship entity. +// If the Friendship 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 *FriendshipMutation) OldFriendID(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldFriendID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldFriendID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldFriendID: %w", err) + } + return oldValue.FriendID, nil +} + +// ResetFriendID resets all changes to the "friend_id" field. +func (m *FriendshipMutation) ResetFriendID() { + m.friend = nil +} + +// ClearUser clears the "user" edge to the User entity. +func (m *FriendshipMutation) ClearUser() { + m.cleareduser = true +} + +// UserCleared reports if the "user" edge to the User entity was cleared. +func (m *FriendshipMutation) UserCleared() bool { + return m.cleareduser +} + +// UserIDs returns the "user" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// UserID instead. It exists only for internal usage by the builders. +func (m *FriendshipMutation) UserIDs() (ids []int) { + if id := m.user; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetUser resets all changes to the "user" edge. +func (m *FriendshipMutation) ResetUser() { + m.user = nil + m.cleareduser = false +} + +// ClearFriend clears the "friend" edge to the User entity. +func (m *FriendshipMutation) ClearFriend() { + m.clearedfriend = true +} + +// FriendCleared reports if the "friend" edge to the User entity was cleared. +func (m *FriendshipMutation) FriendCleared() bool { + return m.clearedfriend +} + +// FriendIDs returns the "friend" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// FriendID instead. It exists only for internal usage by the builders. +func (m *FriendshipMutation) FriendIDs() (ids []int) { + if id := m.friend; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetFriend resets all changes to the "friend" edge. +func (m *FriendshipMutation) ResetFriend() { + m.friend = nil + m.clearedfriend = false +} + +// Where appends a list predicates to the FriendshipMutation builder. +func (m *FriendshipMutation) Where(ps ...predicate.Friendship) { + m.predicates = append(m.predicates, ps...) +} + +// Op returns the operation name. +func (m *FriendshipMutation) Op() Op { + return m.op +} + +// Type returns the node type of this mutation (Friendship). +func (m *FriendshipMutation) 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 *FriendshipMutation) Fields() []string { + fields := make([]string, 0, 4) + if m.weight != nil { + fields = append(fields, friendship.FieldWeight) + } + if m.created_at != nil { + fields = append(fields, friendship.FieldCreatedAt) + } + if m.user != nil { + fields = append(fields, friendship.FieldUserID) + } + if m.friend != nil { + fields = append(fields, friendship.FieldFriendID) + } + 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 *FriendshipMutation) Field(name string) (ent.Value, bool) { + switch name { + case friendship.FieldWeight: + return m.Weight() + case friendship.FieldCreatedAt: + return m.CreatedAt() + case friendship.FieldUserID: + return m.UserID() + case friendship.FieldFriendID: + return m.FriendID() + } + 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 *FriendshipMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case friendship.FieldWeight: + return m.OldWeight(ctx) + case friendship.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case friendship.FieldUserID: + return m.OldUserID(ctx) + case friendship.FieldFriendID: + return m.OldFriendID(ctx) + } + return nil, fmt.Errorf("unknown Friendship 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 *FriendshipMutation) SetField(name string, value ent.Value) error { + switch name { + case friendship.FieldWeight: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetWeight(v) + return nil + case friendship.FieldCreatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreatedAt(v) + return nil + case friendship.FieldUserID: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUserID(v) + return nil + case friendship.FieldFriendID: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetFriendID(v) + return nil + } + return fmt.Errorf("unknown Friendship field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *FriendshipMutation) AddedFields() []string { + var fields []string + if m.addweight != nil { + fields = append(fields, friendship.FieldWeight) + } + 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 *FriendshipMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case friendship.FieldWeight: + return m.AddedWeight() + } + 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 *FriendshipMutation) AddField(name string, value ent.Value) error { + switch name { + case friendship.FieldWeight: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddWeight(v) + return nil + } + return fmt.Errorf("unknown Friendship numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *FriendshipMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *FriendshipMutation) 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 *FriendshipMutation) ClearField(name string) error { + return fmt.Errorf("unknown Friendship 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 *FriendshipMutation) ResetField(name string) error { + switch name { + case friendship.FieldWeight: + m.ResetWeight() + return nil + case friendship.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case friendship.FieldUserID: + m.ResetUserID() + return nil + case friendship.FieldFriendID: + m.ResetFriendID() + return nil + } + return fmt.Errorf("unknown Friendship field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *FriendshipMutation) AddedEdges() []string { + edges := make([]string, 0, 2) + if m.user != nil { + edges = append(edges, friendship.EdgeUser) + } + if m.friend != nil { + edges = append(edges, friendship.EdgeFriend) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *FriendshipMutation) AddedIDs(name string) []ent.Value { + switch name { + case friendship.EdgeUser: + if id := m.user; id != nil { + return []ent.Value{*id} + } + case friendship.EdgeFriend: + if id := m.friend; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *FriendshipMutation) 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 *FriendshipMutation) RemovedIDs(name string) []ent.Value { + switch name { + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *FriendshipMutation) ClearedEdges() []string { + edges := make([]string, 0, 2) + if m.cleareduser { + edges = append(edges, friendship.EdgeUser) + } + if m.clearedfriend { + edges = append(edges, friendship.EdgeFriend) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *FriendshipMutation) EdgeCleared(name string) bool { + switch name { + case friendship.EdgeUser: + return m.cleareduser + case friendship.EdgeFriend: + return m.clearedfriend + } + 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 *FriendshipMutation) ClearEdge(name string) error { + switch name { + case friendship.EdgeUser: + m.ClearUser() + return nil + case friendship.EdgeFriend: + m.ClearFriend() + return nil + } + return fmt.Errorf("unknown Friendship 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 *FriendshipMutation) ResetEdge(name string) error { + switch name { + case friendship.EdgeUser: + m.ResetUser() + return nil + case friendship.EdgeFriend: + m.ResetFriend() + return nil + } + return fmt.Errorf("unknown Friendship edge %s", name) +} + +// GroupMutation represents an operation that mutates the Group nodes in the graph. +type GroupMutation struct { + config + op Op + typ string + id *int + name *string + clearedFields map[string]struct{} + users map[int]struct{} + removedusers map[int]struct{} + clearedusers bool + joined_users map[int]struct{} + removedjoined_users map[int]struct{} + clearedjoined_users bool + done bool + oldValue func(context.Context) (*Group, error) + predicates []predicate.Group +} + +var _ ent.Mutation = (*GroupMutation)(nil) + +// groupOption allows management of the mutation configuration using functional options. +type groupOption func(*GroupMutation) + +// newGroupMutation creates new mutation for the Group entity. +func newGroupMutation(c config, op Op, opts ...groupOption) *GroupMutation { + m := &GroupMutation{ + config: c, + op: op, + typ: TypeGroup, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withGroupID sets the ID field of the mutation. +func withGroupID(id int) groupOption { + return func(m *GroupMutation) { + var ( + err error + once sync.Once + value *Group + ) + m.oldValue = func(ctx context.Context) (*Group, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Group.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withGroup sets the old Group of the mutation. +func withGroup(node *Group) groupOption { + return func(m *GroupMutation) { + m.oldValue = func(context.Context) (*Group, 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 GroupMutation) 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 GroupMutation) 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 *GroupMutation) 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 *GroupMutation) 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().Group.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetName sets the "name" field. +func (m *GroupMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *GroupMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return + } + return *v, true +} + +// OldName returns the old "name" field's value of the Group entity. +// If the Group 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 *GroupMutation) OldName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, nil +} + +// ResetName resets all changes to the "name" field. +func (m *GroupMutation) ResetName() { + m.name = nil +} + +// AddUserIDs adds the "users" edge to the User entity by ids. +func (m *GroupMutation) AddUserIDs(ids ...int) { + if m.users == nil { + m.users = make(map[int]struct{}) + } + for i := range ids { + m.users[ids[i]] = struct{}{} + } +} + +// ClearUsers clears the "users" edge to the User entity. +func (m *GroupMutation) ClearUsers() { + m.clearedusers = true +} + +// UsersCleared reports if the "users" edge to the User entity was cleared. +func (m *GroupMutation) UsersCleared() bool { + return m.clearedusers +} + +// RemoveUserIDs removes the "users" edge to the User entity by IDs. +func (m *GroupMutation) RemoveUserIDs(ids ...int) { + if m.removedusers == nil { + m.removedusers = make(map[int]struct{}) + } + for i := range ids { + delete(m.users, ids[i]) + m.removedusers[ids[i]] = struct{}{} + } +} + +// RemovedUsers returns the removed IDs of the "users" edge to the User entity. +func (m *GroupMutation) RemovedUsersIDs() (ids []int) { + for id := range m.removedusers { + ids = append(ids, id) + } + return +} + +// UsersIDs returns the "users" edge IDs in the mutation. +func (m *GroupMutation) UsersIDs() (ids []int) { + for id := range m.users { + ids = append(ids, id) + } + return +} + +// ResetUsers resets all changes to the "users" edge. +func (m *GroupMutation) ResetUsers() { + m.users = nil + m.clearedusers = false + m.removedusers = nil +} + +// AddJoinedUserIDs adds the "joined_users" edge to the UserGroup entity by ids. +func (m *GroupMutation) AddJoinedUserIDs(ids ...int) { + if m.joined_users == nil { + m.joined_users = make(map[int]struct{}) + } + for i := range ids { + m.joined_users[ids[i]] = struct{}{} + } +} + +// ClearJoinedUsers clears the "joined_users" edge to the UserGroup entity. +func (m *GroupMutation) ClearJoinedUsers() { + m.clearedjoined_users = true +} + +// JoinedUsersCleared reports if the "joined_users" edge to the UserGroup entity was cleared. +func (m *GroupMutation) JoinedUsersCleared() bool { + return m.clearedjoined_users +} + +// RemoveJoinedUserIDs removes the "joined_users" edge to the UserGroup entity by IDs. +func (m *GroupMutation) RemoveJoinedUserIDs(ids ...int) { + if m.removedjoined_users == nil { + m.removedjoined_users = make(map[int]struct{}) + } + for i := range ids { + delete(m.joined_users, ids[i]) + m.removedjoined_users[ids[i]] = struct{}{} + } +} + +// RemovedJoinedUsers returns the removed IDs of the "joined_users" edge to the UserGroup entity. +func (m *GroupMutation) RemovedJoinedUsersIDs() (ids []int) { + for id := range m.removedjoined_users { + ids = append(ids, id) + } + return +} + +// JoinedUsersIDs returns the "joined_users" edge IDs in the mutation. +func (m *GroupMutation) JoinedUsersIDs() (ids []int) { + for id := range m.joined_users { + ids = append(ids, id) + } + return +} + +// ResetJoinedUsers resets all changes to the "joined_users" edge. +func (m *GroupMutation) ResetJoinedUsers() { + m.joined_users = nil + m.clearedjoined_users = false + m.removedjoined_users = nil +} + +// Where appends a list predicates to the GroupMutation builder. +func (m *GroupMutation) Where(ps ...predicate.Group) { + m.predicates = append(m.predicates, ps...) +} + +// Op returns the operation name. +func (m *GroupMutation) Op() Op { + return m.op +} + +// Type returns the node type of this mutation (Group). +func (m *GroupMutation) 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 *GroupMutation) Fields() []string { + fields := make([]string, 0, 1) + if m.name != nil { + fields = append(fields, group.FieldName) + } + 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 *GroupMutation) Field(name string) (ent.Value, bool) { + switch name { + case group.FieldName: + return m.Name() + } + 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 *GroupMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case group.FieldName: + return m.OldName(ctx) + } + return nil, fmt.Errorf("unknown Group 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 *GroupMutation) SetField(name string, value ent.Value) error { + switch name { + case group.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + } + return fmt.Errorf("unknown Group field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *GroupMutation) 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 *GroupMutation) 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 *GroupMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown Group numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *GroupMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *GroupMutation) 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 *GroupMutation) ClearField(name string) error { + return fmt.Errorf("unknown Group 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 *GroupMutation) ResetField(name string) error { + switch name { + case group.FieldName: + m.ResetName() + return nil + } + return fmt.Errorf("unknown Group field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *GroupMutation) AddedEdges() []string { + edges := make([]string, 0, 2) + if m.users != nil { + edges = append(edges, group.EdgeUsers) + } + if m.joined_users != nil { + edges = append(edges, group.EdgeJoinedUsers) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *GroupMutation) AddedIDs(name string) []ent.Value { + switch name { + case group.EdgeUsers: + ids := make([]ent.Value, 0, len(m.users)) + for id := range m.users { + ids = append(ids, id) + } + return ids + case group.EdgeJoinedUsers: + ids := make([]ent.Value, 0, len(m.joined_users)) + for id := range m.joined_users { + ids = append(ids, id) + } + return ids + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *GroupMutation) RemovedEdges() []string { + edges := make([]string, 0, 2) + if m.removedusers != nil { + edges = append(edges, group.EdgeUsers) + } + if m.removedjoined_users != nil { + edges = append(edges, group.EdgeJoinedUsers) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *GroupMutation) RemovedIDs(name string) []ent.Value { + switch name { + case group.EdgeUsers: + ids := make([]ent.Value, 0, len(m.removedusers)) + for id := range m.removedusers { + ids = append(ids, id) + } + return ids + case group.EdgeJoinedUsers: + ids := make([]ent.Value, 0, len(m.removedjoined_users)) + for id := range m.removedjoined_users { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *GroupMutation) ClearedEdges() []string { + edges := make([]string, 0, 2) + if m.clearedusers { + edges = append(edges, group.EdgeUsers) + } + if m.clearedjoined_users { + edges = append(edges, group.EdgeJoinedUsers) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *GroupMutation) EdgeCleared(name string) bool { + switch name { + case group.EdgeUsers: + return m.clearedusers + case group.EdgeJoinedUsers: + return m.clearedjoined_users + } + 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 *GroupMutation) ClearEdge(name string) error { + switch name { + } + return fmt.Errorf("unknown Group 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 *GroupMutation) ResetEdge(name string) error { + switch name { + case group.EdgeUsers: + m.ResetUsers() + return nil + case group.EdgeJoinedUsers: + m.ResetJoinedUsers() + return nil + } + return fmt.Errorf("unknown Group edge %s", name) +} + +// RelationshipMutation represents an operation that mutates the Relationship nodes in the graph. +type RelationshipMutation struct { + config + op Op + typ string + weight *int + addweight *int + clearedFields map[string]struct{} + user *int + cleareduser bool + relative *int + clearedrelative bool + done bool + oldValue func(context.Context) (*Relationship, error) + predicates []predicate.Relationship +} + +var _ ent.Mutation = (*RelationshipMutation)(nil) + +// relationshipOption allows management of the mutation configuration using functional options. +type relationshipOption func(*RelationshipMutation) + +// newRelationshipMutation creates new mutation for the Relationship entity. +func newRelationshipMutation(c config, op Op, opts ...relationshipOption) *RelationshipMutation { + m := &RelationshipMutation{ + config: c, + op: op, + typ: TypeRelationship, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// 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 RelationshipMutation) 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 RelationshipMutation) 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 +} + +// SetWeight sets the "weight" field. +func (m *RelationshipMutation) SetWeight(i int) { + m.weight = &i + m.addweight = nil +} + +// Weight returns the value of the "weight" field in the mutation. +func (m *RelationshipMutation) Weight() (r int, exists bool) { + v := m.weight + if v == nil { + return + } + return *v, true +} + +// AddWeight adds i to the "weight" field. +func (m *RelationshipMutation) AddWeight(i int) { + if m.addweight != nil { + *m.addweight += i + } else { + m.addweight = &i + } +} + +// AddedWeight returns the value that was added to the "weight" field in this mutation. +func (m *RelationshipMutation) AddedWeight() (r int, exists bool) { + v := m.addweight + if v == nil { + return + } + return *v, true +} + +// ResetWeight resets all changes to the "weight" field. +func (m *RelationshipMutation) ResetWeight() { + m.weight = nil + m.addweight = nil +} + +// SetUserID sets the "user_id" field. +func (m *RelationshipMutation) SetUserID(i int) { + m.user = &i +} + +// UserID returns the value of the "user_id" field in the mutation. +func (m *RelationshipMutation) UserID() (r int, exists bool) { + v := m.user + if v == nil { + return + } + return *v, true +} + +// ResetUserID resets all changes to the "user_id" field. +func (m *RelationshipMutation) ResetUserID() { + m.user = nil +} + +// SetRelativeID sets the "relative_id" field. +func (m *RelationshipMutation) SetRelativeID(i int) { + m.relative = &i +} + +// RelativeID returns the value of the "relative_id" field in the mutation. +func (m *RelationshipMutation) RelativeID() (r int, exists bool) { + v := m.relative + if v == nil { + return + } + return *v, true +} + +// ResetRelativeID resets all changes to the "relative_id" field. +func (m *RelationshipMutation) ResetRelativeID() { + m.relative = nil +} + +// ClearUser clears the "user" edge to the User entity. +func (m *RelationshipMutation) ClearUser() { + m.cleareduser = true +} + +// UserCleared reports if the "user" edge to the User entity was cleared. +func (m *RelationshipMutation) UserCleared() bool { + return m.cleareduser +} + +// UserIDs returns the "user" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// UserID instead. It exists only for internal usage by the builders. +func (m *RelationshipMutation) UserIDs() (ids []int) { + if id := m.user; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetUser resets all changes to the "user" edge. +func (m *RelationshipMutation) ResetUser() { + m.user = nil + m.cleareduser = false +} + +// ClearRelative clears the "relative" edge to the User entity. +func (m *RelationshipMutation) ClearRelative() { + m.clearedrelative = true +} + +// RelativeCleared reports if the "relative" edge to the User entity was cleared. +func (m *RelationshipMutation) RelativeCleared() bool { + return m.clearedrelative +} + +// RelativeIDs returns the "relative" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// RelativeID instead. It exists only for internal usage by the builders. +func (m *RelationshipMutation) RelativeIDs() (ids []int) { + if id := m.relative; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetRelative resets all changes to the "relative" edge. +func (m *RelationshipMutation) ResetRelative() { + m.relative = nil + m.clearedrelative = false +} + +// Where appends a list predicates to the RelationshipMutation builder. +func (m *RelationshipMutation) Where(ps ...predicate.Relationship) { + m.predicates = append(m.predicates, ps...) +} + +// Op returns the operation name. +func (m *RelationshipMutation) Op() Op { + return m.op +} + +// Type returns the node type of this mutation (Relationship). +func (m *RelationshipMutation) 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 *RelationshipMutation) Fields() []string { + fields := make([]string, 0, 3) + if m.weight != nil { + fields = append(fields, relationship.FieldWeight) + } + if m.user != nil { + fields = append(fields, relationship.FieldUserID) + } + if m.relative != nil { + fields = append(fields, relationship.FieldRelativeID) + } + 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 *RelationshipMutation) Field(name string) (ent.Value, bool) { + switch name { + case relationship.FieldWeight: + return m.Weight() + case relationship.FieldUserID: + return m.UserID() + case relationship.FieldRelativeID: + return m.RelativeID() + } + 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 *RelationshipMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + return nil, errors.New("edge schema Relationship does not support getting old values") +} + +// 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 *RelationshipMutation) SetField(name string, value ent.Value) error { + switch name { + case relationship.FieldWeight: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetWeight(v) + return nil + case relationship.FieldUserID: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUserID(v) + return nil + case relationship.FieldRelativeID: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRelativeID(v) + return nil + } + return fmt.Errorf("unknown Relationship field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *RelationshipMutation) AddedFields() []string { + var fields []string + if m.addweight != nil { + fields = append(fields, relationship.FieldWeight) + } + 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 *RelationshipMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case relationship.FieldWeight: + return m.AddedWeight() + } + 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 *RelationshipMutation) AddField(name string, value ent.Value) error { + switch name { + case relationship.FieldWeight: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddWeight(v) + return nil + } + return fmt.Errorf("unknown Relationship numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *RelationshipMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *RelationshipMutation) 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 *RelationshipMutation) ClearField(name string) error { + return fmt.Errorf("unknown Relationship 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 *RelationshipMutation) ResetField(name string) error { + switch name { + case relationship.FieldWeight: + m.ResetWeight() + return nil + case relationship.FieldUserID: + m.ResetUserID() + return nil + case relationship.FieldRelativeID: + m.ResetRelativeID() + return nil + } + return fmt.Errorf("unknown Relationship field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *RelationshipMutation) AddedEdges() []string { + edges := make([]string, 0, 2) + if m.user != nil { + edges = append(edges, relationship.EdgeUser) + } + if m.relative != nil { + edges = append(edges, relationship.EdgeRelative) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *RelationshipMutation) AddedIDs(name string) []ent.Value { + switch name { + case relationship.EdgeUser: + if id := m.user; id != nil { + return []ent.Value{*id} + } + case relationship.EdgeRelative: + if id := m.relative; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *RelationshipMutation) 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 *RelationshipMutation) RemovedIDs(name string) []ent.Value { + switch name { + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *RelationshipMutation) ClearedEdges() []string { + edges := make([]string, 0, 2) + if m.cleareduser { + edges = append(edges, relationship.EdgeUser) + } + if m.clearedrelative { + edges = append(edges, relationship.EdgeRelative) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *RelationshipMutation) EdgeCleared(name string) bool { + switch name { + case relationship.EdgeUser: + return m.cleareduser + case relationship.EdgeRelative: + return m.clearedrelative + } + 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 *RelationshipMutation) ClearEdge(name string) error { + switch name { + case relationship.EdgeUser: + m.ClearUser() + return nil + case relationship.EdgeRelative: + m.ClearRelative() + return nil + } + return fmt.Errorf("unknown Relationship 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 *RelationshipMutation) ResetEdge(name string) error { + switch name { + case relationship.EdgeUser: + m.ResetUser() + return nil + case relationship.EdgeRelative: + m.ResetRelative() + return nil + } + return fmt.Errorf("unknown Relationship edge %s", name) +} + +// TweetMutation represents an operation that mutates the Tweet nodes in the graph. +type TweetMutation struct { + config + op Op + typ string + id *int + text *string + clearedFields map[string]struct{} + liked_users map[int]struct{} + removedliked_users map[int]struct{} + clearedliked_users bool + done bool + oldValue func(context.Context) (*Tweet, error) + predicates []predicate.Tweet +} + +var _ ent.Mutation = (*TweetMutation)(nil) + +// tweetOption allows management of the mutation configuration using functional options. +type tweetOption func(*TweetMutation) + +// newTweetMutation creates new mutation for the Tweet entity. +func newTweetMutation(c config, op Op, opts ...tweetOption) *TweetMutation { + m := &TweetMutation{ + config: c, + op: op, + typ: TypeTweet, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withTweetID sets the ID field of the mutation. +func withTweetID(id int) tweetOption { + return func(m *TweetMutation) { + var ( + err error + once sync.Once + value *Tweet + ) + m.oldValue = func(ctx context.Context) (*Tweet, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Tweet.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withTweet sets the old Tweet of the mutation. +func withTweet(node *Tweet) tweetOption { + return func(m *TweetMutation) { + m.oldValue = func(context.Context) (*Tweet, 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 TweetMutation) 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 TweetMutation) 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 *TweetMutation) 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 *TweetMutation) 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().Tweet.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetText sets the "text" field. +func (m *TweetMutation) SetText(s string) { + m.text = &s +} + +// Text returns the value of the "text" field in the mutation. +func (m *TweetMutation) Text() (r string, exists bool) { + v := m.text + if v == nil { + return + } + return *v, true +} + +// OldText returns the old "text" field's value of the Tweet entity. +// If the Tweet 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 *TweetMutation) OldText(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldText is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldText requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldText: %w", err) + } + return oldValue.Text, nil +} + +// ResetText resets all changes to the "text" field. +func (m *TweetMutation) ResetText() { + m.text = nil +} + +// AddLikedUserIDs adds the "liked_users" edge to the User entity by ids. +func (m *TweetMutation) AddLikedUserIDs(ids ...int) { + if m.liked_users == nil { + m.liked_users = make(map[int]struct{}) + } + for i := range ids { + m.liked_users[ids[i]] = struct{}{} + } +} + +// ClearLikedUsers clears the "liked_users" edge to the User entity. +func (m *TweetMutation) ClearLikedUsers() { + m.clearedliked_users = true +} + +// LikedUsersCleared reports if the "liked_users" edge to the User entity was cleared. +func (m *TweetMutation) LikedUsersCleared() bool { + return m.clearedliked_users +} + +// RemoveLikedUserIDs removes the "liked_users" edge to the User entity by IDs. +func (m *TweetMutation) RemoveLikedUserIDs(ids ...int) { + if m.removedliked_users == nil { + m.removedliked_users = make(map[int]struct{}) + } + for i := range ids { + delete(m.liked_users, ids[i]) + m.removedliked_users[ids[i]] = struct{}{} + } +} + +// RemovedLikedUsers returns the removed IDs of the "liked_users" edge to the User entity. +func (m *TweetMutation) RemovedLikedUsersIDs() (ids []int) { + for id := range m.removedliked_users { + ids = append(ids, id) + } + return +} + +// LikedUsersIDs returns the "liked_users" edge IDs in the mutation. +func (m *TweetMutation) LikedUsersIDs() (ids []int) { + for id := range m.liked_users { + ids = append(ids, id) + } + return +} + +// ResetLikedUsers resets all changes to the "liked_users" edge. +func (m *TweetMutation) ResetLikedUsers() { + m.liked_users = nil + m.clearedliked_users = false + m.removedliked_users = nil +} + +// Where appends a list predicates to the TweetMutation builder. +func (m *TweetMutation) Where(ps ...predicate.Tweet) { + m.predicates = append(m.predicates, ps...) +} + +// Op returns the operation name. +func (m *TweetMutation) Op() Op { + return m.op +} + +// Type returns the node type of this mutation (Tweet). +func (m *TweetMutation) 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 *TweetMutation) Fields() []string { + fields := make([]string, 0, 1) + if m.text != nil { + fields = append(fields, tweet.FieldText) + } + 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 *TweetMutation) Field(name string) (ent.Value, bool) { + switch name { + case tweet.FieldText: + return m.Text() + } + 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 *TweetMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case tweet.FieldText: + return m.OldText(ctx) + } + return nil, fmt.Errorf("unknown Tweet 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 *TweetMutation) SetField(name string, value ent.Value) error { + switch name { + case tweet.FieldText: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetText(v) + return nil + } + return fmt.Errorf("unknown Tweet field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *TweetMutation) 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 *TweetMutation) 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 *TweetMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown Tweet numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *TweetMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *TweetMutation) 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 *TweetMutation) ClearField(name string) error { + return fmt.Errorf("unknown Tweet 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 *TweetMutation) ResetField(name string) error { + switch name { + case tweet.FieldText: + m.ResetText() + return nil + } + return fmt.Errorf("unknown Tweet field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *TweetMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.liked_users != nil { + edges = append(edges, tweet.EdgeLikedUsers) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *TweetMutation) AddedIDs(name string) []ent.Value { + switch name { + case tweet.EdgeLikedUsers: + ids := make([]ent.Value, 0, len(m.liked_users)) + for id := range m.liked_users { + 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, 1) + if m.removedliked_users != nil { + edges = append(edges, tweet.EdgeLikedUsers) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *TweetMutation) RemovedIDs(name string) []ent.Value { + switch name { + case tweet.EdgeLikedUsers: + ids := make([]ent.Value, 0, len(m.removedliked_users)) + for id := range m.removedliked_users { + 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, 1) + if m.clearedliked_users { + edges = append(edges, tweet.EdgeLikedUsers) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *TweetMutation) EdgeCleared(name string) bool { + switch name { + case tweet.EdgeLikedUsers: + return m.clearedliked_users + } + 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 *TweetMutation) ClearEdge(name string) error { + switch name { + } + return fmt.Errorf("unknown Tweet 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 *TweetMutation) ResetEdge(name string) error { + switch name { + case tweet.EdgeLikedUsers: + m.ResetLikedUsers() + return nil + } + return fmt.Errorf("unknown Tweet edge %s", name) +} + +// TweetLikeMutation represents an operation that mutates the TweetLike nodes in the graph. +type TweetLikeMutation struct { + config + op Op + typ string + liked_at *time.Time + clearedFields map[string]struct{} + user *int + cleareduser bool + tweet *int + clearedtweet bool + done bool + oldValue func(context.Context) (*TweetLike, error) + predicates []predicate.TweetLike +} + +var _ ent.Mutation = (*TweetLikeMutation)(nil) + +// tweetlikeOption allows management of the mutation configuration using functional options. +type tweetlikeOption func(*TweetLikeMutation) + +// newTweetLikeMutation creates new mutation for the TweetLike entity. +func newTweetLikeMutation(c config, op Op, opts ...tweetlikeOption) *TweetLikeMutation { + m := &TweetLikeMutation{ + config: c, + op: op, + typ: TypeTweetLike, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// 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 TweetLikeMutation) 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 TweetLikeMutation) 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 +} + +// SetLikedAt sets the "liked_at" field. +func (m *TweetLikeMutation) SetLikedAt(t time.Time) { + m.liked_at = &t +} + +// LikedAt returns the value of the "liked_at" field in the mutation. +func (m *TweetLikeMutation) LikedAt() (r time.Time, exists bool) { + v := m.liked_at + if v == nil { + return + } + return *v, true +} + +// ResetLikedAt resets all changes to the "liked_at" field. +func (m *TweetLikeMutation) ResetLikedAt() { + m.liked_at = nil +} + +// SetUserID sets the "user_id" field. +func (m *TweetLikeMutation) SetUserID(i int) { + m.user = &i +} + +// UserID returns the value of the "user_id" field in the mutation. +func (m *TweetLikeMutation) UserID() (r int, exists bool) { + v := m.user + if v == nil { + return + } + return *v, true +} + +// ResetUserID resets all changes to the "user_id" field. +func (m *TweetLikeMutation) ResetUserID() { + m.user = nil +} + +// SetTweetID sets the "tweet_id" field. +func (m *TweetLikeMutation) SetTweetID(i int) { + m.tweet = &i +} + +// TweetID returns the value of the "tweet_id" field in the mutation. +func (m *TweetLikeMutation) TweetID() (r int, exists bool) { + v := m.tweet + if v == nil { + return + } + return *v, true +} + +// ResetTweetID resets all changes to the "tweet_id" field. +func (m *TweetLikeMutation) ResetTweetID() { + m.tweet = nil +} + +// ClearUser clears the "user" edge to the User entity. +func (m *TweetLikeMutation) ClearUser() { + m.cleareduser = true +} + +// UserCleared reports if the "user" edge to the User entity was cleared. +func (m *TweetLikeMutation) UserCleared() bool { + return m.cleareduser +} + +// UserIDs returns the "user" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// UserID instead. It exists only for internal usage by the builders. +func (m *TweetLikeMutation) UserIDs() (ids []int) { + if id := m.user; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetUser resets all changes to the "user" edge. +func (m *TweetLikeMutation) ResetUser() { + m.user = nil + m.cleareduser = false +} + +// ClearTweet clears the "tweet" edge to the Tweet entity. +func (m *TweetLikeMutation) ClearTweet() { + m.clearedtweet = true +} + +// TweetCleared reports if the "tweet" edge to the Tweet entity was cleared. +func (m *TweetLikeMutation) 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 *TweetLikeMutation) TweetIDs() (ids []int) { + if id := m.tweet; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetTweet resets all changes to the "tweet" edge. +func (m *TweetLikeMutation) ResetTweet() { + m.tweet = nil + m.clearedtweet = false +} + +// Where appends a list predicates to the TweetLikeMutation builder. +func (m *TweetLikeMutation) Where(ps ...predicate.TweetLike) { + m.predicates = append(m.predicates, ps...) +} + +// Op returns the operation name. +func (m *TweetLikeMutation) Op() Op { + return m.op +} + +// Type returns the node type of this mutation (TweetLike). +func (m *TweetLikeMutation) 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 *TweetLikeMutation) Fields() []string { + fields := make([]string, 0, 3) + if m.liked_at != nil { + fields = append(fields, tweetlike.FieldLikedAt) + } + if m.user != nil { + fields = append(fields, tweetlike.FieldUserID) + } + if m.tweet != nil { + fields = append(fields, tweetlike.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 *TweetLikeMutation) Field(name string) (ent.Value, bool) { + switch name { + case tweetlike.FieldLikedAt: + return m.LikedAt() + case tweetlike.FieldUserID: + return m.UserID() + case tweetlike.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 *TweetLikeMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + return nil, errors.New("edge schema TweetLike does not support getting old values") +} + +// 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 *TweetLikeMutation) SetField(name string, value ent.Value) error { + switch name { + case tweetlike.FieldLikedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetLikedAt(v) + return nil + case tweetlike.FieldUserID: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUserID(v) + return nil + case tweetlike.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 TweetLike field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *TweetLikeMutation) 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 *TweetLikeMutation) 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 *TweetLikeMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown TweetLike numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *TweetLikeMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *TweetLikeMutation) 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 *TweetLikeMutation) ClearField(name string) error { + return fmt.Errorf("unknown TweetLike 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 *TweetLikeMutation) ResetField(name string) error { + switch name { + case tweetlike.FieldLikedAt: + m.ResetLikedAt() + return nil + case tweetlike.FieldUserID: + m.ResetUserID() + return nil + case tweetlike.FieldTweetID: + m.ResetTweetID() + return nil + } + return fmt.Errorf("unknown TweetLike field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *TweetLikeMutation) AddedEdges() []string { + edges := make([]string, 0, 2) + if m.user != nil { + edges = append(edges, tweetlike.EdgeUser) + } + if m.tweet != nil { + edges = append(edges, tweetlike.EdgeTweet) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *TweetLikeMutation) AddedIDs(name string) []ent.Value { + switch name { + case tweetlike.EdgeUser: + if id := m.user; id != nil { + return []ent.Value{*id} + } + case tweetlike.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 *TweetLikeMutation) 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 *TweetLikeMutation) RemovedIDs(name string) []ent.Value { + switch name { + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *TweetLikeMutation) ClearedEdges() []string { + edges := make([]string, 0, 2) + if m.cleareduser { + edges = append(edges, tweetlike.EdgeUser) + } + if m.clearedtweet { + edges = append(edges, tweetlike.EdgeTweet) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *TweetLikeMutation) EdgeCleared(name string) bool { + switch name { + case tweetlike.EdgeUser: + return m.cleareduser + case tweetlike.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 *TweetLikeMutation) ClearEdge(name string) error { + switch name { + case tweetlike.EdgeUser: + m.ClearUser() + return nil + case tweetlike.EdgeTweet: + m.ClearTweet() + return nil + } + return fmt.Errorf("unknown TweetLike 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 *TweetLikeMutation) ResetEdge(name string) error { + switch name { + case tweetlike.EdgeUser: + m.ResetUser() + return nil + case tweetlike.EdgeTweet: + m.ResetTweet() + return nil + } + return fmt.Errorf("unknown TweetLike edge %s", name) +} + +// UserMutation represents an operation that mutates the User nodes in the graph. +type UserMutation struct { + config + op Op + typ string + id *int + name *string + clearedFields map[string]struct{} + liked_tweets map[int]struct{} + removedliked_tweets map[int]struct{} + clearedliked_tweets bool + groups map[int]struct{} + removedgroups map[int]struct{} + clearedgroups bool + friends map[int]struct{} + removedfriends map[int]struct{} + clearedfriends bool + relatives map[int]struct{} + removedrelatives map[int]struct{} + clearedrelatives bool + joined_groups map[int]struct{} + removedjoined_groups map[int]struct{} + clearedjoined_groups bool + friendships map[int]struct{} + removedfriendships map[int]struct{} + clearedfriendships bool + done bool + oldValue func(context.Context) (*User, error) + predicates []predicate.User +} + +var _ ent.Mutation = (*UserMutation)(nil) + +// userOption allows management of the mutation configuration using functional options. +type userOption func(*UserMutation) + +// newUserMutation creates new mutation for the User entity. +func newUserMutation(c config, op Op, opts ...userOption) *UserMutation { + m := &UserMutation{ + config: c, + op: op, + typ: TypeUser, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withUserID sets the ID field of the mutation. +func withUserID(id int) userOption { + return func(m *UserMutation) { + var ( + err error + once sync.Once + value *User + ) + m.oldValue = func(ctx context.Context) (*User, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().User.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withUser sets the old User of the mutation. +func withUser(node *User) userOption { + return func(m *UserMutation) { + m.oldValue = func(context.Context) (*User, error) { + return node, nil + } + m.id = &node.ID + } +} + +// Client returns a new `ent.Client` from the mutation. If the mutation was +// executed in a transaction (ent.Tx), a transactional client is returned. +func (m UserMutation) Client() *Client { + client := &Client{config: m.config} + client.init() + return client +} + +// Tx returns an `ent.Tx` for mutations that were executed in transactions; +// it returns an error otherwise. +func (m UserMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("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 *UserMutation) ID() (id int, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// IDs queries the database and returns the entity ids that match the mutation's predicate. +// That means, if the mutation is applied within a transaction with an isolation level such +// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated +// or updated by the mutation. +func (m *UserMutation) IDs(ctx context.Context) ([]int, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []int{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().User.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetName sets the "name" field. +func (m *UserMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *UserMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return + } + return *v, true +} + +// OldName returns the old "name" field's value of the User entity. +// If the User object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UserMutation) OldName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, nil +} + +// ResetName resets all changes to the "name" field. +func (m *UserMutation) ResetName() { + m.name = nil +} + +// AddLikedTweetIDs adds the "liked_tweets" edge to the Tweet entity by ids. +func (m *UserMutation) AddLikedTweetIDs(ids ...int) { + if m.liked_tweets == nil { + m.liked_tweets = make(map[int]struct{}) + } + for i := range ids { + m.liked_tweets[ids[i]] = struct{}{} + } +} + +// ClearLikedTweets clears the "liked_tweets" edge to the Tweet entity. +func (m *UserMutation) ClearLikedTweets() { + m.clearedliked_tweets = true +} + +// LikedTweetsCleared reports if the "liked_tweets" edge to the Tweet entity was cleared. +func (m *UserMutation) LikedTweetsCleared() bool { + return m.clearedliked_tweets +} + +// RemoveLikedTweetIDs removes the "liked_tweets" edge to the Tweet entity by IDs. +func (m *UserMutation) RemoveLikedTweetIDs(ids ...int) { + if m.removedliked_tweets == nil { + m.removedliked_tweets = make(map[int]struct{}) + } + for i := range ids { + delete(m.liked_tweets, ids[i]) + m.removedliked_tweets[ids[i]] = struct{}{} + } +} + +// RemovedLikedTweets returns the removed IDs of the "liked_tweets" edge to the Tweet entity. +func (m *UserMutation) RemovedLikedTweetsIDs() (ids []int) { + for id := range m.removedliked_tweets { + ids = append(ids, id) + } + return +} + +// LikedTweetsIDs returns the "liked_tweets" edge IDs in the mutation. +func (m *UserMutation) LikedTweetsIDs() (ids []int) { + for id := range m.liked_tweets { + ids = append(ids, id) + } + return +} + +// ResetLikedTweets resets all changes to the "liked_tweets" edge. +func (m *UserMutation) ResetLikedTweets() { + m.liked_tweets = nil + m.clearedliked_tweets = false + m.removedliked_tweets = nil +} + +// AddGroupIDs adds the "groups" edge to the Group entity by ids. +func (m *UserMutation) AddGroupIDs(ids ...int) { + if m.groups == nil { + m.groups = make(map[int]struct{}) + } + for i := range ids { + m.groups[ids[i]] = struct{}{} + } +} + +// ClearGroups clears the "groups" edge to the Group entity. +func (m *UserMutation) ClearGroups() { + m.clearedgroups = true +} + +// GroupsCleared reports if the "groups" edge to the Group entity was cleared. +func (m *UserMutation) GroupsCleared() bool { + return m.clearedgroups +} + +// RemoveGroupIDs removes the "groups" edge to the Group entity by IDs. +func (m *UserMutation) RemoveGroupIDs(ids ...int) { + if m.removedgroups == nil { + m.removedgroups = make(map[int]struct{}) + } + for i := range ids { + delete(m.groups, ids[i]) + m.removedgroups[ids[i]] = struct{}{} + } +} + +// RemovedGroups returns the removed IDs of the "groups" edge to the Group entity. +func (m *UserMutation) RemovedGroupsIDs() (ids []int) { + for id := range m.removedgroups { + ids = append(ids, id) + } + return +} + +// GroupsIDs returns the "groups" edge IDs in the mutation. +func (m *UserMutation) GroupsIDs() (ids []int) { + for id := range m.groups { + ids = append(ids, id) + } + return +} + +// ResetGroups resets all changes to the "groups" edge. +func (m *UserMutation) ResetGroups() { + m.groups = nil + m.clearedgroups = false + m.removedgroups = nil +} + +// AddFriendIDs adds the "friends" edge to the User entity by ids. +func (m *UserMutation) AddFriendIDs(ids ...int) { + if m.friends == nil { + m.friends = make(map[int]struct{}) + } + for i := range ids { + m.friends[ids[i]] = struct{}{} + } +} + +// ClearFriends clears the "friends" edge to the User entity. +func (m *UserMutation) ClearFriends() { + m.clearedfriends = true +} + +// FriendsCleared reports if the "friends" edge to the User entity was cleared. +func (m *UserMutation) FriendsCleared() bool { + return m.clearedfriends +} + +// RemoveFriendIDs removes the "friends" edge to the User entity by IDs. +func (m *UserMutation) RemoveFriendIDs(ids ...int) { + if m.removedfriends == nil { + m.removedfriends = make(map[int]struct{}) + } + for i := range ids { + delete(m.friends, ids[i]) + m.removedfriends[ids[i]] = struct{}{} + } +} + +// RemovedFriends returns the removed IDs of the "friends" edge to the User entity. +func (m *UserMutation) RemovedFriendsIDs() (ids []int) { + for id := range m.removedfriends { + ids = append(ids, id) + } + return +} + +// FriendsIDs returns the "friends" edge IDs in the mutation. +func (m *UserMutation) FriendsIDs() (ids []int) { + for id := range m.friends { + ids = append(ids, id) + } + return +} + +// ResetFriends resets all changes to the "friends" edge. +func (m *UserMutation) ResetFriends() { + m.friends = nil + m.clearedfriends = false + m.removedfriends = nil +} + +// AddRelativeIDs adds the "relatives" edge to the User entity by ids. +func (m *UserMutation) AddRelativeIDs(ids ...int) { + if m.relatives == nil { + m.relatives = make(map[int]struct{}) + } + for i := range ids { + m.relatives[ids[i]] = struct{}{} + } +} + +// ClearRelatives clears the "relatives" edge to the User entity. +func (m *UserMutation) ClearRelatives() { + m.clearedrelatives = true +} + +// RelativesCleared reports if the "relatives" edge to the User entity was cleared. +func (m *UserMutation) RelativesCleared() bool { + return m.clearedrelatives +} + +// RemoveRelativeIDs removes the "relatives" edge to the User entity by IDs. +func (m *UserMutation) RemoveRelativeIDs(ids ...int) { + if m.removedrelatives == nil { + m.removedrelatives = make(map[int]struct{}) + } + for i := range ids { + delete(m.relatives, ids[i]) + m.removedrelatives[ids[i]] = struct{}{} + } +} + +// RemovedRelatives returns the removed IDs of the "relatives" edge to the User entity. +func (m *UserMutation) RemovedRelativesIDs() (ids []int) { + for id := range m.removedrelatives { + ids = append(ids, id) + } + return +} + +// RelativesIDs returns the "relatives" edge IDs in the mutation. +func (m *UserMutation) RelativesIDs() (ids []int) { + for id := range m.relatives { + ids = append(ids, id) + } + return +} + +// ResetRelatives resets all changes to the "relatives" edge. +func (m *UserMutation) ResetRelatives() { + m.relatives = nil + m.clearedrelatives = false + m.removedrelatives = nil +} + +// AddJoinedGroupIDs adds the "joined_groups" edge to the UserGroup entity by ids. +func (m *UserMutation) AddJoinedGroupIDs(ids ...int) { + if m.joined_groups == nil { + m.joined_groups = make(map[int]struct{}) + } + for i := range ids { + m.joined_groups[ids[i]] = struct{}{} + } +} + +// ClearJoinedGroups clears the "joined_groups" edge to the UserGroup entity. +func (m *UserMutation) ClearJoinedGroups() { + m.clearedjoined_groups = true +} + +// JoinedGroupsCleared reports if the "joined_groups" edge to the UserGroup entity was cleared. +func (m *UserMutation) JoinedGroupsCleared() bool { + return m.clearedjoined_groups +} + +// RemoveJoinedGroupIDs removes the "joined_groups" edge to the UserGroup entity by IDs. +func (m *UserMutation) RemoveJoinedGroupIDs(ids ...int) { + if m.removedjoined_groups == nil { + m.removedjoined_groups = make(map[int]struct{}) + } + for i := range ids { + delete(m.joined_groups, ids[i]) + m.removedjoined_groups[ids[i]] = struct{}{} + } +} + +// RemovedJoinedGroups returns the removed IDs of the "joined_groups" edge to the UserGroup entity. +func (m *UserMutation) RemovedJoinedGroupsIDs() (ids []int) { + for id := range m.removedjoined_groups { + ids = append(ids, id) + } + return +} + +// JoinedGroupsIDs returns the "joined_groups" edge IDs in the mutation. +func (m *UserMutation) JoinedGroupsIDs() (ids []int) { + for id := range m.joined_groups { + ids = append(ids, id) + } + return +} + +// ResetJoinedGroups resets all changes to the "joined_groups" edge. +func (m *UserMutation) ResetJoinedGroups() { + m.joined_groups = nil + m.clearedjoined_groups = false + m.removedjoined_groups = nil +} + +// AddFriendshipIDs adds the "friendships" edge to the Friendship entity by ids. +func (m *UserMutation) AddFriendshipIDs(ids ...int) { + if m.friendships == nil { + m.friendships = make(map[int]struct{}) + } + for i := range ids { + m.friendships[ids[i]] = struct{}{} + } +} + +// ClearFriendships clears the "friendships" edge to the Friendship entity. +func (m *UserMutation) ClearFriendships() { + m.clearedfriendships = true +} + +// FriendshipsCleared reports if the "friendships" edge to the Friendship entity was cleared. +func (m *UserMutation) FriendshipsCleared() bool { + return m.clearedfriendships +} + +// RemoveFriendshipIDs removes the "friendships" edge to the Friendship entity by IDs. +func (m *UserMutation) RemoveFriendshipIDs(ids ...int) { + if m.removedfriendships == nil { + m.removedfriendships = make(map[int]struct{}) + } + for i := range ids { + delete(m.friendships, ids[i]) + m.removedfriendships[ids[i]] = struct{}{} + } +} + +// RemovedFriendships returns the removed IDs of the "friendships" edge to the Friendship entity. +func (m *UserMutation) RemovedFriendshipsIDs() (ids []int) { + for id := range m.removedfriendships { + ids = append(ids, id) + } + return +} + +// FriendshipsIDs returns the "friendships" edge IDs in the mutation. +func (m *UserMutation) FriendshipsIDs() (ids []int) { + for id := range m.friendships { + ids = append(ids, id) + } + return +} + +// ResetFriendships resets all changes to the "friendships" edge. +func (m *UserMutation) ResetFriendships() { + m.friendships = nil + m.clearedfriendships = false + m.removedfriendships = nil +} + +// Where appends a list predicates to the UserMutation builder. +func (m *UserMutation) Where(ps ...predicate.User) { + m.predicates = append(m.predicates, ps...) +} + +// Op returns the operation name. +func (m *UserMutation) Op() Op { + return m.op +} + +// Type returns the node type of this mutation (User). +func (m *UserMutation) Type() string { + return m.typ +} + +// Fields returns all fields that were changed during this mutation. Note that in +// order to get all numeric fields that were incremented/decremented, call +// AddedFields(). +func (m *UserMutation) Fields() []string { + fields := make([]string, 0, 1) + if m.name != nil { + fields = append(fields, user.FieldName) + } + return fields +} + +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. +func (m *UserMutation) Field(name string) (ent.Value, bool) { + switch name { + case user.FieldName: + return m.Name() + } + return nil, false +} + +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. +func (m *UserMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case user.FieldName: + return m.OldName(ctx) + } + return nil, fmt.Errorf("unknown User field %s", name) +} + +// SetField sets the value of a field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *UserMutation) SetField(name string, value ent.Value) error { + switch name { + case user.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + } + return fmt.Errorf("unknown User field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *UserMutation) AddedFields() []string { + 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 *UserMutation) 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 *UserMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown User numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *UserMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *UserMutation) FieldCleared(name string) bool { + _, ok := m.clearedFields[name] + return ok +} + +// ClearField clears the value of the field with the given name. It returns an +// error if the field is not defined in the schema. +func (m *UserMutation) ClearField(name string) error { + return fmt.Errorf("unknown User nullable field %s", name) +} + +// ResetField resets all changes in the mutation for the field with the given name. +// It returns an error if the field is not defined in the schema. +func (m *UserMutation) ResetField(name string) error { + switch name { + case user.FieldName: + m.ResetName() + return nil + } + return fmt.Errorf("unknown User field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *UserMutation) AddedEdges() []string { + edges := make([]string, 0, 6) + if m.liked_tweets != nil { + edges = append(edges, user.EdgeLikedTweets) + } + if m.groups != nil { + edges = append(edges, user.EdgeGroups) + } + if m.friends != nil { + edges = append(edges, user.EdgeFriends) + } + if m.relatives != nil { + edges = append(edges, user.EdgeRelatives) + } + if m.joined_groups != nil { + edges = append(edges, user.EdgeJoinedGroups) + } + if m.friendships != nil { + edges = append(edges, user.EdgeFriendships) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *UserMutation) AddedIDs(name string) []ent.Value { + switch name { + case user.EdgeLikedTweets: + ids := make([]ent.Value, 0, len(m.liked_tweets)) + for id := range m.liked_tweets { + ids = append(ids, id) + } + return ids + case user.EdgeGroups: + ids := make([]ent.Value, 0, len(m.groups)) + for id := range m.groups { + ids = append(ids, id) + } + return ids + case user.EdgeFriends: + ids := make([]ent.Value, 0, len(m.friends)) + for id := range m.friends { + ids = append(ids, id) + } + return ids + case user.EdgeRelatives: + ids := make([]ent.Value, 0, len(m.relatives)) + for id := range m.relatives { + ids = append(ids, id) + } + return ids + case user.EdgeJoinedGroups: + ids := make([]ent.Value, 0, len(m.joined_groups)) + for id := range m.joined_groups { + ids = append(ids, id) + } + return ids + case user.EdgeFriendships: + ids := make([]ent.Value, 0, len(m.friendships)) + for id := range m.friendships { + ids = append(ids, id) + } + return ids + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *UserMutation) RemovedEdges() []string { + edges := make([]string, 0, 6) + if m.removedliked_tweets != nil { + edges = append(edges, user.EdgeLikedTweets) + } + if m.removedgroups != nil { + edges = append(edges, user.EdgeGroups) + } + if m.removedfriends != nil { + edges = append(edges, user.EdgeFriends) + } + if m.removedrelatives != nil { + edges = append(edges, user.EdgeRelatives) + } + if m.removedjoined_groups != nil { + edges = append(edges, user.EdgeJoinedGroups) + } + if m.removedfriendships != nil { + edges = append(edges, user.EdgeFriendships) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *UserMutation) RemovedIDs(name string) []ent.Value { + switch name { + case user.EdgeLikedTweets: + ids := make([]ent.Value, 0, len(m.removedliked_tweets)) + for id := range m.removedliked_tweets { + ids = append(ids, id) + } + return ids + case user.EdgeGroups: + ids := make([]ent.Value, 0, len(m.removedgroups)) + for id := range m.removedgroups { + ids = append(ids, id) + } + return ids + case user.EdgeFriends: + ids := make([]ent.Value, 0, len(m.removedfriends)) + for id := range m.removedfriends { + ids = append(ids, id) + } + return ids + case user.EdgeRelatives: + ids := make([]ent.Value, 0, len(m.removedrelatives)) + for id := range m.removedrelatives { + ids = append(ids, id) + } + return ids + case user.EdgeJoinedGroups: + ids := make([]ent.Value, 0, len(m.removedjoined_groups)) + for id := range m.removedjoined_groups { + ids = append(ids, id) + } + return ids + case user.EdgeFriendships: + ids := make([]ent.Value, 0, len(m.removedfriendships)) + for id := range m.removedfriendships { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *UserMutation) ClearedEdges() []string { + edges := make([]string, 0, 6) + if m.clearedliked_tweets { + edges = append(edges, user.EdgeLikedTweets) + } + if m.clearedgroups { + edges = append(edges, user.EdgeGroups) + } + if m.clearedfriends { + edges = append(edges, user.EdgeFriends) + } + if m.clearedrelatives { + edges = append(edges, user.EdgeRelatives) + } + if m.clearedjoined_groups { + edges = append(edges, user.EdgeJoinedGroups) + } + if m.clearedfriendships { + edges = append(edges, user.EdgeFriendships) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *UserMutation) EdgeCleared(name string) bool { + switch name { + case user.EdgeLikedTweets: + return m.clearedliked_tweets + case user.EdgeGroups: + return m.clearedgroups + case user.EdgeFriends: + return m.clearedfriends + case user.EdgeRelatives: + return m.clearedrelatives + case user.EdgeJoinedGroups: + return m.clearedjoined_groups + case user.EdgeFriendships: + return m.clearedfriendships + } + return false +} + +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. +func (m *UserMutation) ClearEdge(name string) error { + switch name { + } + return fmt.Errorf("unknown User unique edge %s", name) +} + +// ResetEdge resets all changes to the edge with the given name in this mutation. +// It returns an error if the edge is not defined in the schema. +func (m *UserMutation) ResetEdge(name string) error { + switch name { + case user.EdgeLikedTweets: + m.ResetLikedTweets() + return nil + case user.EdgeGroups: + m.ResetGroups() + return nil + case user.EdgeFriends: + m.ResetFriends() + return nil + case user.EdgeRelatives: + m.ResetRelatives() + return nil + case user.EdgeJoinedGroups: + m.ResetJoinedGroups() + return nil + case user.EdgeFriendships: + m.ResetFriendships() + return nil + } + return fmt.Errorf("unknown User edge %s", name) +} + +// UserGroupMutation represents an operation that mutates the UserGroup nodes in the graph. +type UserGroupMutation struct { + config + op Op + typ string + id *int + joined_at *time.Time + clearedFields map[string]struct{} + user *int + cleareduser bool + group *int + clearedgroup bool + done bool + oldValue func(context.Context) (*UserGroup, error) + predicates []predicate.UserGroup +} + +var _ ent.Mutation = (*UserGroupMutation)(nil) + +// usergroupOption allows management of the mutation configuration using functional options. +type usergroupOption func(*UserGroupMutation) + +// newUserGroupMutation creates new mutation for the UserGroup entity. +func newUserGroupMutation(c config, op Op, opts ...usergroupOption) *UserGroupMutation { + m := &UserGroupMutation{ + config: c, + op: op, + typ: TypeUserGroup, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withUserGroupID sets the ID field of the mutation. +func withUserGroupID(id int) usergroupOption { + return func(m *UserGroupMutation) { + var ( + err error + once sync.Once + value *UserGroup + ) + m.oldValue = func(ctx context.Context) (*UserGroup, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().UserGroup.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withUserGroup sets the old UserGroup of the mutation. +func withUserGroup(node *UserGroup) usergroupOption { + return func(m *UserGroupMutation) { + m.oldValue = func(context.Context) (*UserGroup, 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 UserGroupMutation) 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 UserGroupMutation) 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 *UserGroupMutation) 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 *UserGroupMutation) 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().UserGroup.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetJoinedAt sets the "joined_at" field. +func (m *UserGroupMutation) SetJoinedAt(t time.Time) { + m.joined_at = &t +} + +// JoinedAt returns the value of the "joined_at" field in the mutation. +func (m *UserGroupMutation) JoinedAt() (r time.Time, exists bool) { + v := m.joined_at + if v == nil { + return + } + return *v, true +} + +// OldJoinedAt returns the old "joined_at" field's value of the UserGroup entity. +// If the UserGroup 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 *UserGroupMutation) OldJoinedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldJoinedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldJoinedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldJoinedAt: %w", err) + } + return oldValue.JoinedAt, nil +} + +// ResetJoinedAt resets all changes to the "joined_at" field. +func (m *UserGroupMutation) ResetJoinedAt() { + m.joined_at = nil +} + +// SetUserID sets the "user_id" field. +func (m *UserGroupMutation) SetUserID(i int) { + m.user = &i +} + +// UserID returns the value of the "user_id" field in the mutation. +func (m *UserGroupMutation) UserID() (r int, exists bool) { + v := m.user + if v == nil { + return + } + return *v, true +} + +// OldUserID returns the old "user_id" field's value of the UserGroup entity. +// If the UserGroup 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 *UserGroupMutation) OldUserID(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUserID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUserID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUserID: %w", err) + } + return oldValue.UserID, nil +} + +// ResetUserID resets all changes to the "user_id" field. +func (m *UserGroupMutation) ResetUserID() { + m.user = nil +} + +// SetGroupID sets the "group_id" field. +func (m *UserGroupMutation) SetGroupID(i int) { + m.group = &i +} + +// GroupID returns the value of the "group_id" field in the mutation. +func (m *UserGroupMutation) GroupID() (r int, exists bool) { + v := m.group + if v == nil { + return + } + return *v, true +} + +// OldGroupID returns the old "group_id" field's value of the UserGroup entity. +// If the UserGroup 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 *UserGroupMutation) OldGroupID(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldGroupID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldGroupID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldGroupID: %w", err) + } + return oldValue.GroupID, nil +} + +// ResetGroupID resets all changes to the "group_id" field. +func (m *UserGroupMutation) ResetGroupID() { + m.group = nil +} + +// ClearUser clears the "user" edge to the User entity. +func (m *UserGroupMutation) ClearUser() { + m.cleareduser = true +} + +// UserCleared reports if the "user" edge to the User entity was cleared. +func (m *UserGroupMutation) UserCleared() bool { + return m.cleareduser +} + +// UserIDs returns the "user" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// UserID instead. It exists only for internal usage by the builders. +func (m *UserGroupMutation) UserIDs() (ids []int) { + if id := m.user; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetUser resets all changes to the "user" edge. +func (m *UserGroupMutation) ResetUser() { + m.user = nil + m.cleareduser = false +} + +// ClearGroup clears the "group" edge to the Group entity. +func (m *UserGroupMutation) ClearGroup() { + m.clearedgroup = true +} + +// GroupCleared reports if the "group" edge to the Group entity was cleared. +func (m *UserGroupMutation) GroupCleared() bool { + return m.clearedgroup +} + +// GroupIDs returns the "group" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// GroupID instead. It exists only for internal usage by the builders. +func (m *UserGroupMutation) GroupIDs() (ids []int) { + if id := m.group; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetGroup resets all changes to the "group" edge. +func (m *UserGroupMutation) ResetGroup() { + m.group = nil + m.clearedgroup = false +} + +// Where appends a list predicates to the UserGroupMutation builder. +func (m *UserGroupMutation) Where(ps ...predicate.UserGroup) { + m.predicates = append(m.predicates, ps...) +} + +// Op returns the operation name. +func (m *UserGroupMutation) Op() Op { + return m.op +} + +// Type returns the node type of this mutation (UserGroup). +func (m *UserGroupMutation) 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 *UserGroupMutation) Fields() []string { + fields := make([]string, 0, 3) + if m.joined_at != nil { + fields = append(fields, usergroup.FieldJoinedAt) + } + if m.user != nil { + fields = append(fields, usergroup.FieldUserID) + } + if m.group != nil { + fields = append(fields, usergroup.FieldGroupID) + } + 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 *UserGroupMutation) Field(name string) (ent.Value, bool) { + switch name { + case usergroup.FieldJoinedAt: + return m.JoinedAt() + case usergroup.FieldUserID: + return m.UserID() + case usergroup.FieldGroupID: + return m.GroupID() + } + 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 *UserGroupMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case usergroup.FieldJoinedAt: + return m.OldJoinedAt(ctx) + case usergroup.FieldUserID: + return m.OldUserID(ctx) + case usergroup.FieldGroupID: + return m.OldGroupID(ctx) + } + return nil, fmt.Errorf("unknown UserGroup 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 *UserGroupMutation) SetField(name string, value ent.Value) error { + switch name { + case usergroup.FieldJoinedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetJoinedAt(v) + return nil + case usergroup.FieldUserID: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUserID(v) + return nil + case usergroup.FieldGroupID: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetGroupID(v) + return nil + } + return fmt.Errorf("unknown UserGroup field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *UserGroupMutation) 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 *UserGroupMutation) 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 *UserGroupMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown UserGroup numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *UserGroupMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *UserGroupMutation) 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 *UserGroupMutation) ClearField(name string) error { + return fmt.Errorf("unknown UserGroup 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 *UserGroupMutation) ResetField(name string) error { + switch name { + case usergroup.FieldJoinedAt: + m.ResetJoinedAt() + return nil + case usergroup.FieldUserID: + m.ResetUserID() + return nil + case usergroup.FieldGroupID: + m.ResetGroupID() + return nil + } + return fmt.Errorf("unknown UserGroup field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *UserGroupMutation) AddedEdges() []string { + edges := make([]string, 0, 2) + if m.user != nil { + edges = append(edges, usergroup.EdgeUser) + } + if m.group != nil { + edges = append(edges, usergroup.EdgeGroup) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *UserGroupMutation) AddedIDs(name string) []ent.Value { + switch name { + case usergroup.EdgeUser: + if id := m.user; id != nil { + return []ent.Value{*id} + } + case usergroup.EdgeGroup: + if id := m.group; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *UserGroupMutation) 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 *UserGroupMutation) RemovedIDs(name string) []ent.Value { + switch name { + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *UserGroupMutation) ClearedEdges() []string { + edges := make([]string, 0, 2) + if m.cleareduser { + edges = append(edges, usergroup.EdgeUser) + } + if m.clearedgroup { + edges = append(edges, usergroup.EdgeGroup) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *UserGroupMutation) EdgeCleared(name string) bool { + switch name { + case usergroup.EdgeUser: + return m.cleareduser + case usergroup.EdgeGroup: + return m.clearedgroup + } + 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 *UserGroupMutation) ClearEdge(name string) error { + switch name { + case usergroup.EdgeUser: + m.ClearUser() + return nil + case usergroup.EdgeGroup: + m.ClearGroup() + return nil + } + return fmt.Errorf("unknown UserGroup 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 *UserGroupMutation) ResetEdge(name string) error { + switch name { + case usergroup.EdgeUser: + m.ResetUser() + return nil + case usergroup.EdgeGroup: + m.ResetGroup() + return nil + } + return fmt.Errorf("unknown UserGroup edge %s", name) +} diff --git a/entc/integration/edgeschema/ent/predicate/predicate.go b/entc/integration/edgeschema/ent/predicate/predicate.go new file mode 100644 index 0000000000..2a3a027e2d --- /dev/null +++ b/entc/integration/edgeschema/ent/predicate/predicate.go @@ -0,0 +1,28 @@ +// Code generated by entc, DO NOT EDIT. + +package predicate + +import ( + "entgo.io/ent/dialect/sql" +) + +// Friendship is the predicate function for friendship builders. +type Friendship func(*sql.Selector) + +// Group is the predicate function for group builders. +type Group func(*sql.Selector) + +// Relationship is the predicate function for relationship builders. +type Relationship 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) + +// User is the predicate function for user builders. +type User func(*sql.Selector) + +// UserGroup is the predicate function for usergroup builders. +type UserGroup func(*sql.Selector) diff --git a/entc/integration/edgeschema/ent/relationship.go b/entc/integration/edgeschema/ent/relationship.go new file mode 100644 index 0000000000..df6918b4e3 --- /dev/null +++ b/entc/integration/edgeschema/ent/relationship.go @@ -0,0 +1,163 @@ +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "fmt" + "strings" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/entc/integration/edgeschema/ent/relationship" + "entgo.io/ent/entc/integration/edgeschema/ent/user" +) + +// Relationship is the model entity for the Relationship schema. +type Relationship struct { + config `json:"-"` + // Weight holds the value of the "weight" field. + Weight int `json:"weight,omitempty"` + // UserID holds the value of the "user_id" field. + UserID int `json:"user_id,omitempty"` + // RelativeID holds the value of the "relative_id" field. + RelativeID int `json:"relative_id,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the RelationshipQuery when eager-loading is set. + Edges RelationshipEdges `json:"edges"` +} + +// RelationshipEdges holds the relations/edges for other nodes in the graph. +type RelationshipEdges struct { + // User holds the value of the user edge. + User *User `json:"user,omitempty"` + // Relative holds the value of the relative edge. + Relative *User `json:"relative,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [2]bool +} + +// UserOrErr returns the User value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e RelationshipEdges) UserOrErr() (*User, error) { + if e.loadedTypes[0] { + if e.User == nil { + // The edge user was loaded in eager-loading, + // but was not found. + return nil, &NotFoundError{label: user.Label} + } + return e.User, nil + } + return nil, &NotLoadedError{edge: "user"} +} + +// RelativeOrErr returns the Relative value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e RelationshipEdges) RelativeOrErr() (*User, error) { + if e.loadedTypes[1] { + if e.Relative == nil { + // The edge relative was loaded in eager-loading, + // but was not found. + return nil, &NotFoundError{label: user.Label} + } + return e.Relative, nil + } + return nil, &NotLoadedError{edge: "relative"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*Relationship) scanValues(columns []string) ([]interface{}, error) { + values := make([]interface{}, len(columns)) + for i := range columns { + switch columns[i] { + case relationship.FieldWeight, relationship.FieldUserID, relationship.FieldRelativeID: + values[i] = new(sql.NullInt64) + default: + return nil, fmt.Errorf("unexpected column %q for type Relationship", columns[i]) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the Relationship fields. +func (r *Relationship) 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 relationship.FieldWeight: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field weight", values[i]) + } else if value.Valid { + r.Weight = int(value.Int64) + } + case relationship.FieldUserID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field user_id", values[i]) + } else if value.Valid { + r.UserID = int(value.Int64) + } + case relationship.FieldRelativeID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field relative_id", values[i]) + } else if value.Valid { + r.RelativeID = int(value.Int64) + } + } + } + return nil +} + +// QueryUser queries the "user" edge of the Relationship entity. +func (r *Relationship) QueryUser() *UserQuery { + return (&RelationshipClient{config: r.config}).QueryUser(r) +} + +// QueryRelative queries the "relative" edge of the Relationship entity. +func (r *Relationship) QueryRelative() *UserQuery { + return (&RelationshipClient{config: r.config}).QueryRelative(r) +} + +// Update returns a builder for updating this Relationship. +// Note that you need to call Relationship.Unwrap() before calling this method if this Relationship +// was returned from a transaction, and the transaction was committed or rolled back. +func (r *Relationship) Update() *RelationshipUpdateOne { + return (&RelationshipClient{config: r.config}).UpdateOne(r) +} + +// Unwrap unwraps the Relationship entity that was returned from a transaction after it was closed, +// so that all future queries will be executed through the driver which created the transaction. +func (r *Relationship) Unwrap() *Relationship { + tx, ok := r.config.driver.(*txDriver) + if !ok { + panic("ent: Relationship is not a transactional entity") + } + r.config.driver = tx.drv + return r +} + +// String implements the fmt.Stringer. +func (r *Relationship) String() string { + var builder strings.Builder + builder.WriteString("Relationship(") + builder.WriteString("weight=") + builder.WriteString(fmt.Sprintf("%v", r.Weight)) + builder.WriteString(", ") + builder.WriteString("user_id=") + builder.WriteString(fmt.Sprintf("%v", r.UserID)) + builder.WriteString(", ") + builder.WriteString("relative_id=") + builder.WriteString(fmt.Sprintf("%v", r.RelativeID)) + builder.WriteByte(')') + return builder.String() +} + +// Relationships is a parsable slice of Relationship. +type Relationships []*Relationship + +func (r Relationships) config(cfg config) { + for _i := range r { + r[_i].config = cfg + } +} diff --git a/entc/integration/edgeschema/ent/relationship/relationship.go b/entc/integration/edgeschema/ent/relationship/relationship.go new file mode 100644 index 0000000000..1a23a7a4a1 --- /dev/null +++ b/entc/integration/edgeschema/ent/relationship/relationship.go @@ -0,0 +1,58 @@ +// Code generated by entc, DO NOT EDIT. + +package relationship + +const ( + // Label holds the string label denoting the relationship type in the database. + Label = "relationship" + // FieldWeight holds the string denoting the weight field in the database. + FieldWeight = "weight" + // FieldUserID holds the string denoting the user_id field in the database. + FieldUserID = "user_id" + // FieldRelativeID holds the string denoting the relative_id field in the database. + FieldRelativeID = "relative_id" + // EdgeUser holds the string denoting the user edge name in mutations. + EdgeUser = "user" + // EdgeRelative holds the string denoting the relative edge name in mutations. + EdgeRelative = "relative" + // UserFieldID holds the string denoting the ID field of the User. + UserFieldID = "id" + // Table holds the table name of the relationship in the database. + Table = "relationships" + // UserTable is the table that holds the user relation/edge. + UserTable = "relationships" + // 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" + // UserColumn is the table column denoting the user relation/edge. + UserColumn = "user_id" + // RelativeTable is the table that holds the relative relation/edge. + RelativeTable = "relationships" + // RelativeInverseTable is the table name for the User entity. + // It exists in this package in order to avoid circular dependency with the "user" package. + RelativeInverseTable = "users" + // RelativeColumn is the table column denoting the relative relation/edge. + RelativeColumn = "relative_id" +) + +// Columns holds all SQL columns for relationship fields. +var Columns = []string{ + FieldWeight, + FieldUserID, + FieldRelativeID, +} + +// 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 ( + // DefaultWeight holds the default value on creation for the "weight" field. + DefaultWeight int +) diff --git a/entc/integration/edgeschema/ent/relationship/where.go b/entc/integration/edgeschema/ent/relationship/where.go new file mode 100644 index 0000000000..d924970b61 --- /dev/null +++ b/entc/integration/edgeschema/ent/relationship/where.go @@ -0,0 +1,290 @@ +// Code generated by entc, DO NOT EDIT. + +package relationship + +import ( + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/edgeschema/ent/predicate" +) + +// Weight applies equality check predicate on the "weight" field. It's identical to WeightEQ. +func Weight(v int) predicate.Relationship { + return predicate.Relationship(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldWeight), v)) + }) +} + +// UserID applies equality check predicate on the "user_id" field. It's identical to UserIDEQ. +func UserID(v int) predicate.Relationship { + return predicate.Relationship(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldUserID), v)) + }) +} + +// RelativeID applies equality check predicate on the "relative_id" field. It's identical to RelativeIDEQ. +func RelativeID(v int) predicate.Relationship { + return predicate.Relationship(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldRelativeID), v)) + }) +} + +// WeightEQ applies the EQ predicate on the "weight" field. +func WeightEQ(v int) predicate.Relationship { + return predicate.Relationship(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldWeight), v)) + }) +} + +// WeightNEQ applies the NEQ predicate on the "weight" field. +func WeightNEQ(v int) predicate.Relationship { + return predicate.Relationship(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldWeight), v)) + }) +} + +// WeightIn applies the In predicate on the "weight" field. +func WeightIn(vs ...int) predicate.Relationship { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Relationship(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(FieldWeight), v...)) + }) +} + +// WeightNotIn applies the NotIn predicate on the "weight" field. +func WeightNotIn(vs ...int) predicate.Relationship { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Relationship(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(FieldWeight), v...)) + }) +} + +// WeightGT applies the GT predicate on the "weight" field. +func WeightGT(v int) predicate.Relationship { + return predicate.Relationship(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldWeight), v)) + }) +} + +// WeightGTE applies the GTE predicate on the "weight" field. +func WeightGTE(v int) predicate.Relationship { + return predicate.Relationship(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldWeight), v)) + }) +} + +// WeightLT applies the LT predicate on the "weight" field. +func WeightLT(v int) predicate.Relationship { + return predicate.Relationship(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldWeight), v)) + }) +} + +// WeightLTE applies the LTE predicate on the "weight" field. +func WeightLTE(v int) predicate.Relationship { + return predicate.Relationship(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldWeight), v)) + }) +} + +// UserIDEQ applies the EQ predicate on the "user_id" field. +func UserIDEQ(v int) predicate.Relationship { + return predicate.Relationship(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldUserID), v)) + }) +} + +// UserIDNEQ applies the NEQ predicate on the "user_id" field. +func UserIDNEQ(v int) predicate.Relationship { + return predicate.Relationship(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldUserID), v)) + }) +} + +// UserIDIn applies the In predicate on the "user_id" field. +func UserIDIn(vs ...int) predicate.Relationship { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Relationship(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(FieldUserID), v...)) + }) +} + +// UserIDNotIn applies the NotIn predicate on the "user_id" field. +func UserIDNotIn(vs ...int) predicate.Relationship { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Relationship(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(FieldUserID), v...)) + }) +} + +// RelativeIDEQ applies the EQ predicate on the "relative_id" field. +func RelativeIDEQ(v int) predicate.Relationship { + return predicate.Relationship(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldRelativeID), v)) + }) +} + +// RelativeIDNEQ applies the NEQ predicate on the "relative_id" field. +func RelativeIDNEQ(v int) predicate.Relationship { + return predicate.Relationship(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldRelativeID), v)) + }) +} + +// RelativeIDIn applies the In predicate on the "relative_id" field. +func RelativeIDIn(vs ...int) predicate.Relationship { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Relationship(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(FieldRelativeID), v...)) + }) +} + +// RelativeIDNotIn applies the NotIn predicate on the "relative_id" field. +func RelativeIDNotIn(vs ...int) predicate.Relationship { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Relationship(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(FieldRelativeID), v...)) + }) +} + +// HasUser applies the HasEdge predicate on the "user" edge. +func HasUser() predicate.Relationship { + return predicate.Relationship(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, UserColumn), + sqlgraph.To(UserInverseTable, UserFieldID), + sqlgraph.Edge(sqlgraph.M2O, false, UserTable, UserColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasUserWith applies the HasEdge predicate on the "user" edge with a given conditions (other predicates). +func HasUserWith(preds ...predicate.User) predicate.Relationship { + return predicate.Relationship(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, UserColumn), + sqlgraph.To(UserInverseTable, UserFieldID), + sqlgraph.Edge(sqlgraph.M2O, false, UserTable, UserColumn), + ) + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasRelative applies the HasEdge predicate on the "relative" edge. +func HasRelative() predicate.Relationship { + return predicate.Relationship(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, RelativeColumn), + sqlgraph.To(RelativeInverseTable, UserFieldID), + sqlgraph.Edge(sqlgraph.M2O, false, RelativeTable, RelativeColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasRelativeWith applies the HasEdge predicate on the "relative" edge with a given conditions (other predicates). +func HasRelativeWith(preds ...predicate.User) predicate.Relationship { + return predicate.Relationship(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, RelativeColumn), + sqlgraph.To(RelativeInverseTable, UserFieldID), + sqlgraph.Edge(sqlgraph.M2O, false, RelativeTable, RelativeColumn), + ) + 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.Relationship) predicate.Relationship { + return predicate.Relationship(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.Relationship) predicate.Relationship { + return predicate.Relationship(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.Relationship) predicate.Relationship { + return predicate.Relationship(func(s *sql.Selector) { + p(s.Not()) + }) +} diff --git a/entc/integration/edgeschema/ent/relationship_create.go b/entc/integration/edgeschema/ent/relationship_create.go new file mode 100644 index 0000000000..5f7a919f4d --- /dev/null +++ b/entc/integration/edgeschema/ent/relationship_create.go @@ -0,0 +1,306 @@ +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/edgeschema/ent/relationship" + "entgo.io/ent/entc/integration/edgeschema/ent/user" + "entgo.io/ent/schema/field" +) + +// RelationshipCreate is the builder for creating a Relationship entity. +type RelationshipCreate struct { + config + mutation *RelationshipMutation + hooks []Hook +} + +// SetWeight sets the "weight" field. +func (rc *RelationshipCreate) SetWeight(i int) *RelationshipCreate { + rc.mutation.SetWeight(i) + return rc +} + +// SetNillableWeight sets the "weight" field if the given value is not nil. +func (rc *RelationshipCreate) SetNillableWeight(i *int) *RelationshipCreate { + if i != nil { + rc.SetWeight(*i) + } + return rc +} + +// SetUserID sets the "user_id" field. +func (rc *RelationshipCreate) SetUserID(i int) *RelationshipCreate { + rc.mutation.SetUserID(i) + return rc +} + +// SetRelativeID sets the "relative_id" field. +func (rc *RelationshipCreate) SetRelativeID(i int) *RelationshipCreate { + rc.mutation.SetRelativeID(i) + return rc +} + +// SetUser sets the "user" edge to the User entity. +func (rc *RelationshipCreate) SetUser(u *User) *RelationshipCreate { + return rc.SetUserID(u.ID) +} + +// SetRelative sets the "relative" edge to the User entity. +func (rc *RelationshipCreate) SetRelative(u *User) *RelationshipCreate { + return rc.SetRelativeID(u.ID) +} + +// Mutation returns the RelationshipMutation object of the builder. +func (rc *RelationshipCreate) Mutation() *RelationshipMutation { + return rc.mutation +} + +// Save creates the Relationship in the database. +func (rc *RelationshipCreate) Save(ctx context.Context) (*Relationship, error) { + var ( + err error + node *Relationship + ) + rc.defaults() + if len(rc.hooks) == 0 { + if err = rc.check(); err != nil { + return nil, err + } + node, err = rc.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*RelationshipMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err = rc.check(); err != nil { + return nil, err + } + rc.mutation = mutation + if node, err = rc.sqlSave(ctx); err != nil { + return nil, err + } + return node, err + }) + for i := len(rc.hooks) - 1; i >= 0; i-- { + if rc.hooks[i] == nil { + return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = rc.hooks[i](mut) + } + v, err := mut.Mutate(ctx, rc.mutation) + if err != nil { + return nil, err + } + nv, ok := v.(*Relationship) + if !ok { + return nil, fmt.Errorf("unexpected node type %T returned from RelationshipMutation", v) + } + node = nv + } + return node, err +} + +// SaveX calls Save and panics if Save returns an error. +func (rc *RelationshipCreate) SaveX(ctx context.Context) *Relationship { + v, err := rc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (rc *RelationshipCreate) Exec(ctx context.Context) error { + _, err := rc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (rc *RelationshipCreate) ExecX(ctx context.Context) { + if err := rc.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (rc *RelationshipCreate) defaults() { + if _, ok := rc.mutation.Weight(); !ok { + v := relationship.DefaultWeight + rc.mutation.SetWeight(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (rc *RelationshipCreate) check() error { + if _, ok := rc.mutation.Weight(); !ok { + return &ValidationError{Name: "weight", err: errors.New(`ent: missing required field "Relationship.weight"`)} + } + if _, ok := rc.mutation.UserID(); !ok { + return &ValidationError{Name: "user_id", err: errors.New(`ent: missing required field "Relationship.user_id"`)} + } + if _, ok := rc.mutation.RelativeID(); !ok { + return &ValidationError{Name: "relative_id", err: errors.New(`ent: missing required field "Relationship.relative_id"`)} + } + if _, ok := rc.mutation.UserID(); !ok { + return &ValidationError{Name: "user", err: errors.New(`ent: missing required edge "Relationship.user"`)} + } + if _, ok := rc.mutation.RelativeID(); !ok { + return &ValidationError{Name: "relative", err: errors.New(`ent: missing required edge "Relationship.relative"`)} + } + return nil +} + +func (rc *RelationshipCreate) sqlSave(ctx context.Context) (*Relationship, error) { + _node, _spec := rc.createSpec() + if err := sqlgraph.CreateNode(ctx, rc.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return nil, err + } + return _node, nil +} + +func (rc *RelationshipCreate) createSpec() (*Relationship, *sqlgraph.CreateSpec) { + var ( + _node = &Relationship{config: rc.config} + _spec = &sqlgraph.CreateSpec{ + Table: relationship.Table, + } + ) + if value, ok := rc.mutation.Weight(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: relationship.FieldWeight, + }) + _node.Weight = value + } + if nodes := rc.mutation.UserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: relationship.UserTable, + Columns: []string{relationship.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.UserID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := rc.mutation.RelativeIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: relationship.RelativeTable, + Columns: []string{relationship.RelativeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.RelativeID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// RelationshipCreateBulk is the builder for creating many Relationship entities in bulk. +type RelationshipCreateBulk struct { + config + builders []*RelationshipCreate +} + +// Save creates the Relationship entities in the database. +func (rcb *RelationshipCreateBulk) Save(ctx context.Context) ([]*Relationship, error) { + specs := make([]*sqlgraph.CreateSpec, len(rcb.builders)) + nodes := make([]*Relationship, len(rcb.builders)) + mutators := make([]Mutator, len(rcb.builders)) + for i := range rcb.builders { + func(i int, root context.Context) { + builder := rcb.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*RelationshipMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + nodes[i], specs[i] = builder.createSpec() + var err error + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, rcb.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, rcb.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + } + } + if err != nil { + return nil, err + } + mutation.done = true + return nodes[i], nil + }) + for i := len(builder.hooks) - 1; i >= 0; i-- { + mut = builder.hooks[i](mut) + } + mutators[i] = mut + }(i, ctx) + } + if len(mutators) > 0 { + if _, err := mutators[0].Mutate(ctx, rcb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (rcb *RelationshipCreateBulk) SaveX(ctx context.Context) []*Relationship { + v, err := rcb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (rcb *RelationshipCreateBulk) Exec(ctx context.Context) error { + _, err := rcb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (rcb *RelationshipCreateBulk) ExecX(ctx context.Context) { + if err := rcb.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/entc/integration/edgeschema/ent/relationship_delete.go b/entc/integration/edgeschema/ent/relationship_delete.go new file mode 100644 index 0000000000..72c0e6e3e9 --- /dev/null +++ b/entc/integration/edgeschema/ent/relationship_delete.go @@ -0,0 +1,106 @@ +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "fmt" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/edgeschema/ent/predicate" + "entgo.io/ent/entc/integration/edgeschema/ent/relationship" +) + +// RelationshipDelete is the builder for deleting a Relationship entity. +type RelationshipDelete struct { + config + hooks []Hook + mutation *RelationshipMutation +} + +// Where appends a list predicates to the RelationshipDelete builder. +func (rd *RelationshipDelete) Where(ps ...predicate.Relationship) *RelationshipDelete { + rd.mutation.Where(ps...) + return rd +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (rd *RelationshipDelete) Exec(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(rd.hooks) == 0 { + affected, err = rd.sqlExec(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*RelationshipMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + rd.mutation = mutation + affected, err = rd.sqlExec(ctx) + mutation.done = true + return affected, err + }) + for i := len(rd.hooks) - 1; i >= 0; i-- { + if rd.hooks[i] == nil { + return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = rd.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, rd.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// ExecX is like Exec, but panics if an error occurs. +func (rd *RelationshipDelete) ExecX(ctx context.Context) int { + n, err := rd.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (rd *RelationshipDelete) sqlExec(ctx context.Context) (int, error) { + _spec := &sqlgraph.DeleteSpec{ + Node: &sqlgraph.NodeSpec{ + Table: relationship.Table, + }, + } + if ps := rd.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return sqlgraph.DeleteNodes(ctx, rd.driver, _spec) +} + +// RelationshipDeleteOne is the builder for deleting a single Relationship entity. +type RelationshipDeleteOne struct { + rd *RelationshipDelete +} + +// Exec executes the deletion query. +func (rdo *RelationshipDeleteOne) Exec(ctx context.Context) error { + n, err := rdo.rd.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{relationship.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (rdo *RelationshipDeleteOne) ExecX(ctx context.Context) { + rdo.rd.ExecX(ctx) +} diff --git a/entc/integration/edgeschema/ent/relationship_query.go b/entc/integration/edgeschema/ent/relationship_query.go new file mode 100644 index 0000000000..9034edcca3 --- /dev/null +++ b/entc/integration/edgeschema/ent/relationship_query.go @@ -0,0 +1,579 @@ +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "fmt" + "math" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/edgeschema/ent/predicate" + "entgo.io/ent/entc/integration/edgeschema/ent/relationship" + "entgo.io/ent/entc/integration/edgeschema/ent/user" +) + +// RelationshipQuery is the builder for querying Relationship entities. +type RelationshipQuery struct { + config + limit *int + offset *int + unique *bool + order []OrderFunc + fields []string + predicates []predicate.Relationship + // eager-loading edges. + withUser *UserQuery + withRelative *UserQuery + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the RelationshipQuery builder. +func (rq *RelationshipQuery) Where(ps ...predicate.Relationship) *RelationshipQuery { + rq.predicates = append(rq.predicates, ps...) + return rq +} + +// Limit adds a limit step to the query. +func (rq *RelationshipQuery) Limit(limit int) *RelationshipQuery { + rq.limit = &limit + return rq +} + +// Offset adds an offset step to the query. +func (rq *RelationshipQuery) Offset(offset int) *RelationshipQuery { + rq.offset = &offset + return rq +} + +// Unique configures the query builder to filter duplicate records on query. +// By default, unique is set to true, and can be disabled using this method. +func (rq *RelationshipQuery) Unique(unique bool) *RelationshipQuery { + rq.unique = &unique + return rq +} + +// Order adds an order step to the query. +func (rq *RelationshipQuery) Order(o ...OrderFunc) *RelationshipQuery { + rq.order = append(rq.order, o...) + return rq +} + +// QueryUser chains the current query on the "user" edge. +func (rq *RelationshipQuery) QueryUser() *UserQuery { + query := &UserQuery{config: rq.config} + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := rq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := rq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(relationship.Table, relationship.UserColumn, selector), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, relationship.UserTable, relationship.UserColumn), + ) + fromU = sqlgraph.SetNeighbors(rq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryRelative chains the current query on the "relative" edge. +func (rq *RelationshipQuery) QueryRelative() *UserQuery { + query := &UserQuery{config: rq.config} + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := rq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := rq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(relationship.Table, relationship.RelativeColumn, selector), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, relationship.RelativeTable, relationship.RelativeColumn), + ) + fromU = sqlgraph.SetNeighbors(rq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first Relationship entity from the query. +// Returns a *NotFoundError when no Relationship was found. +func (rq *RelationshipQuery) First(ctx context.Context) (*Relationship, error) { + nodes, err := rq.Limit(1).All(ctx) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{relationship.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (rq *RelationshipQuery) FirstX(ctx context.Context) *Relationship { + node, err := rq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// Only returns a single Relationship entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Relationship entity is found. +// Returns a *NotFoundError when no Relationship entities are found. +func (rq *RelationshipQuery) Only(ctx context.Context) (*Relationship, error) { + nodes, err := rq.Limit(2).All(ctx) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{relationship.Label} + default: + return nil, &NotSingularError{relationship.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (rq *RelationshipQuery) OnlyX(ctx context.Context) *Relationship { + node, err := rq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// All executes the query and returns a list of Relationships. +func (rq *RelationshipQuery) All(ctx context.Context) ([]*Relationship, error) { + if err := rq.prepareQuery(ctx); err != nil { + return nil, err + } + return rq.sqlAll(ctx) +} + +// AllX is like All, but panics if an error occurs. +func (rq *RelationshipQuery) AllX(ctx context.Context) []*Relationship { + nodes, err := rq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// Count returns the count of the given query. +func (rq *RelationshipQuery) Count(ctx context.Context) (int, error) { + if err := rq.prepareQuery(ctx); err != nil { + return 0, err + } + return rq.sqlCount(ctx) +} + +// CountX is like Count, but panics if an error occurs. +func (rq *RelationshipQuery) CountX(ctx context.Context) int { + count, err := rq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (rq *RelationshipQuery) Exist(ctx context.Context) (bool, error) { + if err := rq.prepareQuery(ctx); err != nil { + return false, err + } + return rq.sqlExist(ctx) +} + +// ExistX is like Exist, but panics if an error occurs. +func (rq *RelationshipQuery) ExistX(ctx context.Context) bool { + exist, err := rq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the RelationshipQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (rq *RelationshipQuery) Clone() *RelationshipQuery { + if rq == nil { + return nil + } + return &RelationshipQuery{ + config: rq.config, + limit: rq.limit, + offset: rq.offset, + order: append([]OrderFunc{}, rq.order...), + predicates: append([]predicate.Relationship{}, rq.predicates...), + withUser: rq.withUser.Clone(), + withRelative: rq.withRelative.Clone(), + // clone intermediate query. + sql: rq.sql.Clone(), + path: rq.path, + unique: rq.unique, + } +} + +// WithUser tells the query-builder to eager-load the nodes that are connected to +// the "user" edge. The optional arguments are used to configure the query builder of the edge. +func (rq *RelationshipQuery) WithUser(opts ...func(*UserQuery)) *RelationshipQuery { + query := &UserQuery{config: rq.config} + for _, opt := range opts { + opt(query) + } + rq.withUser = query + return rq +} + +// WithRelative tells the query-builder to eager-load the nodes that are connected to +// the "relative" edge. The optional arguments are used to configure the query builder of the edge. +func (rq *RelationshipQuery) WithRelative(opts ...func(*UserQuery)) *RelationshipQuery { + query := &UserQuery{config: rq.config} + for _, opt := range opts { + opt(query) + } + rq.withRelative = query + return rq +} + +// 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 { +// Weight int `json:"weight,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.Relationship.Query(). +// GroupBy(relationship.FieldWeight). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +// +func (rq *RelationshipQuery) GroupBy(field string, fields ...string) *RelationshipGroupBy { + grbuild := &RelationshipGroupBy{config: rq.config} + grbuild.fields = append([]string{field}, fields...) + grbuild.path = func(ctx context.Context) (prev *sql.Selector, err error) { + if err := rq.prepareQuery(ctx); err != nil { + return nil, err + } + return rq.sqlQuery(ctx), nil + } + grbuild.label = relationship.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 { +// Weight int `json:"weight,omitempty"` +// } +// +// client.Relationship.Query(). +// Select(relationship.FieldWeight). +// Scan(ctx, &v) +// +func (rq *RelationshipQuery) Select(fields ...string) *RelationshipSelect { + rq.fields = append(rq.fields, fields...) + selbuild := &RelationshipSelect{RelationshipQuery: rq} + selbuild.label = relationship.Label + selbuild.flds, selbuild.scan = &rq.fields, selbuild.Scan + return selbuild +} + +func (rq *RelationshipQuery) prepareQuery(ctx context.Context) error { + for _, f := range rq.fields { + if !relationship.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if rq.path != nil { + prev, err := rq.path(ctx) + if err != nil { + return err + } + rq.sql = prev + } + return nil +} + +func (rq *RelationshipQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Relationship, error) { + var ( + nodes = []*Relationship{} + _spec = rq.querySpec() + loadedTypes = [2]bool{ + rq.withUser != nil, + rq.withRelative != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]interface{}, error) { + return (*Relationship).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []interface{}) error { + node := &Relationship{config: rq.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, rq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + + if query := rq.withUser; query != nil { + ids := make([]int, 0, len(nodes)) + nodeids := make(map[int][]*Relationship) + for i := range nodes { + fk := nodes[i].UserID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + query.Where(user.IDIn(ids...)) + neighbors, err := query.All(ctx) + if err != nil { + return nil, err + } + for _, n := range neighbors { + nodes, ok := nodeids[n.ID] + if !ok { + return nil, fmt.Errorf(`unexpected foreign-key "user_id" returned %v`, n.ID) + } + for i := range nodes { + nodes[i].Edges.User = n + } + } + } + + if query := rq.withRelative; query != nil { + ids := make([]int, 0, len(nodes)) + nodeids := make(map[int][]*Relationship) + for i := range nodes { + fk := nodes[i].RelativeID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + query.Where(user.IDIn(ids...)) + neighbors, err := query.All(ctx) + if err != nil { + return nil, err + } + for _, n := range neighbors { + nodes, ok := nodeids[n.ID] + if !ok { + return nil, fmt.Errorf(`unexpected foreign-key "relative_id" returned %v`, n.ID) + } + for i := range nodes { + nodes[i].Edges.Relative = n + } + } + } + + return nodes, nil +} + +func (rq *RelationshipQuery) sqlCount(ctx context.Context) (int, error) { + _spec := rq.querySpec() + _spec.Unique = false + _spec.Node.Columns = nil + return sqlgraph.CountNodes(ctx, rq.driver, _spec) +} + +func (rq *RelationshipQuery) sqlExist(ctx context.Context) (bool, error) { + n, err := rq.sqlCount(ctx) + if err != nil { + return false, fmt.Errorf("ent: check existence: %w", err) + } + return n > 0, nil +} + +func (rq *RelationshipQuery) querySpec() *sqlgraph.QuerySpec { + _spec := &sqlgraph.QuerySpec{ + Node: &sqlgraph.NodeSpec{ + Table: relationship.Table, + Columns: relationship.Columns, + }, + From: rq.sql, + Unique: true, + } + if unique := rq.unique; unique != nil { + _spec.Unique = *unique + } + if fields := rq.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + for i := range fields { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if ps := rq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := rq.limit; limit != nil { + _spec.Limit = *limit + } + if offset := rq.offset; offset != nil { + _spec.Offset = *offset + } + if ps := rq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (rq *RelationshipQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(rq.driver.Dialect()) + t1 := builder.Table(relationship.Table) + columns := rq.fields + if len(columns) == 0 { + columns = relationship.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if rq.sql != nil { + selector = rq.sql + selector.Select(selector.Columns(columns...)...) + } + if rq.unique != nil && *rq.unique { + selector.Distinct() + } + for _, p := range rq.predicates { + p(selector) + } + for _, p := range rq.order { + p(selector) + } + if offset := rq.offset; offset != nil { + // limit is mandatory for offset clause. We start + // with default value, and override it below if needed. + selector.Offset(*offset).Limit(math.MaxInt32) + } + if limit := rq.limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// RelationshipGroupBy is the group-by builder for Relationship entities. +type RelationshipGroupBy struct { + config + selector + fields []string + fns []AggregateFunc + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (rgb *RelationshipGroupBy) Aggregate(fns ...AggregateFunc) *RelationshipGroupBy { + rgb.fns = append(rgb.fns, fns...) + return rgb +} + +// Scan applies the group-by query and scans the result into the given value. +func (rgb *RelationshipGroupBy) Scan(ctx context.Context, v interface{}) error { + query, err := rgb.path(ctx) + if err != nil { + return err + } + rgb.sql = query + return rgb.sqlScan(ctx, v) +} + +func (rgb *RelationshipGroupBy) sqlScan(ctx context.Context, v interface{}) error { + for _, f := range rgb.fields { + if !relationship.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)} + } + } + selector := rgb.sqlQuery() + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := rgb.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +func (rgb *RelationshipGroupBy) sqlQuery() *sql.Selector { + selector := rgb.sql.Select() + aggregation := make([]string, 0, len(rgb.fns)) + for _, fn := range rgb.fns { + aggregation = append(aggregation, fn(selector)) + } + // If no columns were selected in a custom aggregation function, the default + // selection is the fields used for "group-by", and the aggregation functions. + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(rgb.fields)+len(rgb.fns)) + for _, f := range rgb.fields { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + return selector.GroupBy(selector.Columns(rgb.fields...)...) +} + +// RelationshipSelect is the builder for selecting fields of Relationship entities. +type RelationshipSelect struct { + *RelationshipQuery + selector + // intermediate query (i.e. traversal path). + sql *sql.Selector +} + +// Scan applies the selector query and scans the result into the given value. +func (rs *RelationshipSelect) Scan(ctx context.Context, v interface{}) error { + if err := rs.prepareQuery(ctx); err != nil { + return err + } + rs.sql = rs.RelationshipQuery.sqlQuery(ctx) + return rs.sqlScan(ctx, v) +} + +func (rs *RelationshipSelect) sqlScan(ctx context.Context, v interface{}) error { + rows := &sql.Rows{} + query, args := rs.sql.Query() + if err := rs.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/entc/integration/edgeschema/ent/relationship_update.go b/entc/integration/edgeschema/ent/relationship_update.go new file mode 100644 index 0000000000..258dc3236a --- /dev/null +++ b/entc/integration/edgeschema/ent/relationship_update.go @@ -0,0 +1,542 @@ +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/edgeschema/ent/predicate" + "entgo.io/ent/entc/integration/edgeschema/ent/relationship" + "entgo.io/ent/entc/integration/edgeschema/ent/user" + "entgo.io/ent/schema/field" +) + +// RelationshipUpdate is the builder for updating Relationship entities. +type RelationshipUpdate struct { + config + hooks []Hook + mutation *RelationshipMutation +} + +// Where appends a list predicates to the RelationshipUpdate builder. +func (ru *RelationshipUpdate) Where(ps ...predicate.Relationship) *RelationshipUpdate { + ru.mutation.Where(ps...) + return ru +} + +// SetWeight sets the "weight" field. +func (ru *RelationshipUpdate) SetWeight(i int) *RelationshipUpdate { + ru.mutation.ResetWeight() + ru.mutation.SetWeight(i) + return ru +} + +// SetNillableWeight sets the "weight" field if the given value is not nil. +func (ru *RelationshipUpdate) SetNillableWeight(i *int) *RelationshipUpdate { + if i != nil { + ru.SetWeight(*i) + } + return ru +} + +// AddWeight adds i to the "weight" field. +func (ru *RelationshipUpdate) AddWeight(i int) *RelationshipUpdate { + ru.mutation.AddWeight(i) + return ru +} + +// SetUserID sets the "user_id" field. +func (ru *RelationshipUpdate) SetUserID(i int) *RelationshipUpdate { + ru.mutation.SetUserID(i) + return ru +} + +// SetRelativeID sets the "relative_id" field. +func (ru *RelationshipUpdate) SetRelativeID(i int) *RelationshipUpdate { + ru.mutation.SetRelativeID(i) + return ru +} + +// SetUser sets the "user" edge to the User entity. +func (ru *RelationshipUpdate) SetUser(u *User) *RelationshipUpdate { + return ru.SetUserID(u.ID) +} + +// SetRelative sets the "relative" edge to the User entity. +func (ru *RelationshipUpdate) SetRelative(u *User) *RelationshipUpdate { + return ru.SetRelativeID(u.ID) +} + +// Mutation returns the RelationshipMutation object of the builder. +func (ru *RelationshipUpdate) Mutation() *RelationshipMutation { + return ru.mutation +} + +// ClearUser clears the "user" edge to the User entity. +func (ru *RelationshipUpdate) ClearUser() *RelationshipUpdate { + ru.mutation.ClearUser() + return ru +} + +// ClearRelative clears the "relative" edge to the User entity. +func (ru *RelationshipUpdate) ClearRelative() *RelationshipUpdate { + ru.mutation.ClearRelative() + return ru +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (ru *RelationshipUpdate) Save(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(ru.hooks) == 0 { + if err = ru.check(); err != nil { + return 0, err + } + affected, err = ru.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*RelationshipMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err = ru.check(); err != nil { + return 0, err + } + ru.mutation = mutation + affected, err = ru.sqlSave(ctx) + mutation.done = true + return affected, err + }) + for i := len(ru.hooks) - 1; i >= 0; i-- { + if ru.hooks[i] == nil { + return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = ru.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, ru.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// SaveX is like Save, but panics if an error occurs. +func (ru *RelationshipUpdate) SaveX(ctx context.Context) int { + affected, err := ru.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (ru *RelationshipUpdate) Exec(ctx context.Context) error { + _, err := ru.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (ru *RelationshipUpdate) ExecX(ctx context.Context) { + if err := ru.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (ru *RelationshipUpdate) check() error { + if _, ok := ru.mutation.UserID(); ru.mutation.UserCleared() && !ok { + return errors.New(`ent: clearing a required unique edge "Relationship.user"`) + } + if _, ok := ru.mutation.RelativeID(); ru.mutation.RelativeCleared() && !ok { + return errors.New(`ent: clearing a required unique edge "Relationship.relative"`) + } + return nil +} + +func (ru *RelationshipUpdate) sqlSave(ctx context.Context) (n int, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: relationship.Table, + Columns: relationship.Columns, + }, + } + if ps := ru.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := ru.mutation.Weight(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: relationship.FieldWeight, + }) + } + if value, ok := ru.mutation.AddedWeight(); ok { + _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: relationship.FieldWeight, + }) + } + if ru.mutation.UserCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: relationship.UserTable, + Columns: []string{relationship.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := ru.mutation.UserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: relationship.UserTable, + Columns: []string{relationship.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if ru.mutation.RelativeCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: relationship.RelativeTable, + Columns: []string{relationship.RelativeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := ru.mutation.RelativeIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: relationship.RelativeTable, + Columns: []string{relationship.RelativeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if n, err = sqlgraph.UpdateNodes(ctx, ru.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{relationship.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return 0, err + } + return n, nil +} + +// RelationshipUpdateOne is the builder for updating a single Relationship entity. +type RelationshipUpdateOne struct { + config + fields []string + hooks []Hook + mutation *RelationshipMutation +} + +// SetWeight sets the "weight" field. +func (ruo *RelationshipUpdateOne) SetWeight(i int) *RelationshipUpdateOne { + ruo.mutation.ResetWeight() + ruo.mutation.SetWeight(i) + return ruo +} + +// SetNillableWeight sets the "weight" field if the given value is not nil. +func (ruo *RelationshipUpdateOne) SetNillableWeight(i *int) *RelationshipUpdateOne { + if i != nil { + ruo.SetWeight(*i) + } + return ruo +} + +// AddWeight adds i to the "weight" field. +func (ruo *RelationshipUpdateOne) AddWeight(i int) *RelationshipUpdateOne { + ruo.mutation.AddWeight(i) + return ruo +} + +// SetUserID sets the "user_id" field. +func (ruo *RelationshipUpdateOne) SetUserID(i int) *RelationshipUpdateOne { + ruo.mutation.SetUserID(i) + return ruo +} + +// SetRelativeID sets the "relative_id" field. +func (ruo *RelationshipUpdateOne) SetRelativeID(i int) *RelationshipUpdateOne { + ruo.mutation.SetRelativeID(i) + return ruo +} + +// SetUser sets the "user" edge to the User entity. +func (ruo *RelationshipUpdateOne) SetUser(u *User) *RelationshipUpdateOne { + return ruo.SetUserID(u.ID) +} + +// SetRelative sets the "relative" edge to the User entity. +func (ruo *RelationshipUpdateOne) SetRelative(u *User) *RelationshipUpdateOne { + return ruo.SetRelativeID(u.ID) +} + +// Mutation returns the RelationshipMutation object of the builder. +func (ruo *RelationshipUpdateOne) Mutation() *RelationshipMutation { + return ruo.mutation +} + +// ClearUser clears the "user" edge to the User entity. +func (ruo *RelationshipUpdateOne) ClearUser() *RelationshipUpdateOne { + ruo.mutation.ClearUser() + return ruo +} + +// ClearRelative clears the "relative" edge to the User entity. +func (ruo *RelationshipUpdateOne) ClearRelative() *RelationshipUpdateOne { + ruo.mutation.ClearRelative() + return ruo +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (ruo *RelationshipUpdateOne) Select(field string, fields ...string) *RelationshipUpdateOne { + ruo.fields = append([]string{field}, fields...) + return ruo +} + +// Save executes the query and returns the updated Relationship entity. +func (ruo *RelationshipUpdateOne) Save(ctx context.Context) (*Relationship, error) { + var ( + err error + node *Relationship + ) + if len(ruo.hooks) == 0 { + if err = ruo.check(); err != nil { + return nil, err + } + node, err = ruo.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*RelationshipMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err = ruo.check(); err != nil { + return nil, err + } + ruo.mutation = mutation + node, err = ruo.sqlSave(ctx) + mutation.done = true + return node, err + }) + for i := len(ruo.hooks) - 1; i >= 0; i-- { + if ruo.hooks[i] == nil { + return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = ruo.hooks[i](mut) + } + v, err := mut.Mutate(ctx, ruo.mutation) + if err != nil { + return nil, err + } + nv, ok := v.(*Relationship) + if !ok { + return nil, fmt.Errorf("unexpected node type %T returned from RelationshipMutation", v) + } + node = nv + } + return node, err +} + +// SaveX is like Save, but panics if an error occurs. +func (ruo *RelationshipUpdateOne) SaveX(ctx context.Context) *Relationship { + node, err := ruo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (ruo *RelationshipUpdateOne) Exec(ctx context.Context) error { + _, err := ruo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (ruo *RelationshipUpdateOne) ExecX(ctx context.Context) { + if err := ruo.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (ruo *RelationshipUpdateOne) check() error { + if _, ok := ruo.mutation.UserID(); ruo.mutation.UserCleared() && !ok { + return errors.New(`ent: clearing a required unique edge "Relationship.user"`) + } + if _, ok := ruo.mutation.RelativeID(); ruo.mutation.RelativeCleared() && !ok { + return errors.New(`ent: clearing a required unique edge "Relationship.relative"`) + } + return nil +} + +func (ruo *RelationshipUpdateOne) sqlSave(ctx context.Context) (_node *Relationship, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: relationship.Table, + Columns: relationship.Columns, + }, + } + if fields := ruo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, len(fields)) + for i, f := range fields { + if !relationship.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + _spec.Node.Columns[i] = f + } + } + if ps := ruo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := ruo.mutation.Weight(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: relationship.FieldWeight, + }) + } + if value, ok := ruo.mutation.AddedWeight(); ok { + _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: relationship.FieldWeight, + }) + } + if ruo.mutation.UserCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: relationship.UserTable, + Columns: []string{relationship.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := ruo.mutation.UserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: relationship.UserTable, + Columns: []string{relationship.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if ruo.mutation.RelativeCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: relationship.RelativeTable, + Columns: []string{relationship.RelativeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := ruo.mutation.RelativeIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: relationship.RelativeTable, + Columns: []string{relationship.RelativeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &Relationship{config: ruo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, ruo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{relationship.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return nil, err + } + return _node, nil +} diff --git a/entc/integration/edgeschema/ent/runtime.go b/entc/integration/edgeschema/ent/runtime.go new file mode 100644 index 0000000000..a5979827e2 --- /dev/null +++ b/entc/integration/edgeschema/ent/runtime.go @@ -0,0 +1,61 @@ +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "time" + + "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/schema" + "entgo.io/ent/entc/integration/edgeschema/ent/tweetlike" + "entgo.io/ent/entc/integration/edgeschema/ent/user" + "entgo.io/ent/entc/integration/edgeschema/ent/usergroup" +) + +// The init function reads all schema descriptors with runtime code +// (default values, validators, hooks and policies) and stitches it +// to their package variables. +func init() { + friendshipFields := schema.Friendship{}.Fields() + _ = friendshipFields + // friendshipDescWeight is the schema descriptor for weight field. + friendshipDescWeight := friendshipFields[0].Descriptor() + // friendship.DefaultWeight holds the default value on creation for the weight field. + friendship.DefaultWeight = friendshipDescWeight.Default.(int) + // friendshipDescCreatedAt is the schema descriptor for created_at field. + friendshipDescCreatedAt := friendshipFields[1].Descriptor() + // friendship.DefaultCreatedAt holds the default value on creation for the created_at field. + friendship.DefaultCreatedAt = friendshipDescCreatedAt.Default.(func() time.Time) + groupFields := schema.Group{}.Fields() + _ = groupFields + // groupDescName is the schema descriptor for name field. + groupDescName := groupFields[0].Descriptor() + // group.DefaultName holds the default value on creation for the name field. + group.DefaultName = groupDescName.Default.(string) + relationshipFields := schema.Relationship{}.Fields() + _ = relationshipFields + // relationshipDescWeight is the schema descriptor for weight field. + relationshipDescWeight := relationshipFields[0].Descriptor() + // relationship.DefaultWeight holds the default value on creation for the weight field. + relationship.DefaultWeight = relationshipDescWeight.Default.(int) + tweetlikeFields := schema.TweetLike{}.Fields() + _ = tweetlikeFields + // tweetlikeDescLikedAt is the schema descriptor for liked_at field. + tweetlikeDescLikedAt := tweetlikeFields[0].Descriptor() + // tweetlike.DefaultLikedAt holds the default value on creation for the liked_at field. + tweetlike.DefaultLikedAt = tweetlikeDescLikedAt.Default.(func() time.Time) + userFields := schema.User{}.Fields() + _ = userFields + // userDescName is the schema descriptor for name field. + userDescName := userFields[0].Descriptor() + // user.DefaultName holds the default value on creation for the name field. + user.DefaultName = userDescName.Default.(string) + usergroupFields := schema.UserGroup{}.Fields() + _ = usergroupFields + // usergroupDescJoinedAt is the schema descriptor for joined_at field. + usergroupDescJoinedAt := usergroupFields[0].Descriptor() + // usergroup.DefaultJoinedAt holds the default value on creation for the joined_at field. + usergroup.DefaultJoinedAt = usergroupDescJoinedAt.Default.(func() time.Time) +} diff --git a/entc/integration/edgeschema/ent/runtime/runtime.go b/entc/integration/edgeschema/ent/runtime/runtime.go new file mode 100644 index 0000000000..a95f8f0e89 --- /dev/null +++ b/entc/integration/edgeschema/ent/runtime/runtime.go @@ -0,0 +1,9 @@ +// Code generated by entc, DO NOT EDIT. + +package runtime + +// The schema-stitching logic is generated in entgo.io/ent/entc/integration/edgeschema/ent/runtime.go + +const ( + Version = "(devel)" // Version of ent codegen. +) diff --git a/entc/integration/edgeschema/ent/schema/friendship.go b/entc/integration/edgeschema/ent/schema/friendship.go new file mode 100644 index 0000000000..bf7d33250d --- /dev/null +++ b/entc/integration/edgeschema/ent/schema/friendship.go @@ -0,0 +1,44 @@ +// 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" +) + +// Friendship holds the schema definition for the Friendship entity. +type Friendship struct { + ent.Schema +} + +// Fields of the Friendship. +func (Friendship) Fields() []ent.Field { + return []ent.Field{ + field.Int("weight"). + Default(1), + field.Time("created_at"). + Default(time.Now), + field.Int("user_id"), + field.Int("friend_id"), + } +} + +// Edges of the Friendship. +func (Friendship) Edges() []ent.Edge { + return []ent.Edge{ + edge.To("user", User.Type). + Required(). + Unique(). + Field("user_id"), + edge.To("friend", User.Type). + Required(). + Unique(). + Field("friend_id"), + } +} diff --git a/entc/integration/edgeschema/ent/schema/group.go b/entc/integration/edgeschema/ent/schema/group.go new file mode 100644 index 0000000000..a5e745bd7d --- /dev/null +++ b/entc/integration/edgeschema/ent/schema/group.go @@ -0,0 +1,33 @@ +// 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" +) + +// Group holds the schema definition for the Group entity. +type Group struct { + ent.Schema +} + +// Fields of the Group. +func (Group) Fields() []ent.Field { + return []ent.Field{ + field.String("name"). + Default("Unknown"), + } +} + +// Edges of the Group. +func (Group) Edges() []ent.Edge { + return []ent.Edge{ + edge.From("users", User.Type). + Ref("groups"). + Through("joined_users", UserGroup.Type), + } +} diff --git a/entc/integration/edgeschema/ent/schema/relationship.go b/entc/integration/edgeschema/ent/schema/relationship.go new file mode 100644 index 0000000000..3d44895710 --- /dev/null +++ b/entc/integration/edgeschema/ent/schema/relationship.go @@ -0,0 +1,47 @@ +// 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" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" +) + +// Relationship holds the schema definition for the Relationship entity. +type Relationship struct { + ent.Schema +} + +func (Relationship) Annotations() []schema.Annotation { + return []schema.Annotation{ + field.ID("user_id", "relative_id"), + } +} + +// Fields of the Relationship. +func (Relationship) Fields() []ent.Field { + return []ent.Field{ + field.Int("weight"). + Default(1), + field.Int("user_id"), + field.Int("relative_id"), + } +} + +// Edges of the Relationship. +func (Relationship) Edges() []ent.Edge { + return []ent.Edge{ + edge.To("user", User.Type). + Required(). + Unique(). + Field("user_id"), + edge.To("relative", User.Type). + Required(). + Unique(). + Field("relative_id"), + } +} diff --git a/entc/integration/edgeschema/ent/schema/tweet.go b/entc/integration/edgeschema/ent/schema/tweet.go new file mode 100644 index 0000000000..27e2b2568f --- /dev/null +++ b/entc/integration/edgeschema/ent/schema/tweet.go @@ -0,0 +1,32 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +package schema + +import ( + "entgo.io/ent" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" +) + +// Tweet holds the schema definition for the Tweet entity. +type Tweet struct { + ent.Schema +} + +// Fields of the Tweet. +func (Tweet) Fields() []ent.Field { + return []ent.Field{ + field.Text("text"), + } +} + +// Edges of the Tweet. +func (Tweet) Edges() []ent.Edge { + return []ent.Edge{ + edge.From("liked_users", User.Type). + Ref("liked_tweets"). + Through("likes", TweetLike.Type), + } +} diff --git a/entc/integration/edgeschema/ent/schema/tweetlike.go b/entc/integration/edgeschema/ent/schema/tweetlike.go new file mode 100644 index 0000000000..8e122dae77 --- /dev/null +++ b/entc/integration/edgeschema/ent/schema/tweetlike.go @@ -0,0 +1,49 @@ +// 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" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" +) + +// TweetLike holds the schema definition for the TweetLike entity. +type TweetLike struct { + ent.Schema +} + +func (TweetLike) Annotations() []schema.Annotation { + return []schema.Annotation{ + field.ID("user_id", "tweet_id"), + } +} + +// Fields of the TweetLike. +func (TweetLike) Fields() []ent.Field { + return []ent.Field{ + field.Time("liked_at"). + Default(time.Now), + field.Int("user_id"), + field.Int("tweet_id"), + } +} + +// Edges of the TweetLike. +func (TweetLike) Edges() []ent.Edge { + return []ent.Edge{ + edge.To("user", User.Type). + Unique(). + Required(). + Field("user_id"), + edge.To("tweet", Tweet.Type). + Unique(). + Required(). + Field("tweet_id"), + } +} diff --git a/entc/integration/edgeschema/ent/schema/user.go b/entc/integration/edgeschema/ent/schema/user.go new file mode 100644 index 0000000000..3802a1b880 --- /dev/null +++ b/entc/integration/edgeschema/ent/schema/user.go @@ -0,0 +1,38 @@ +// 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" +) + +// User holds the schema definition for the User entity. +type User struct { + ent.Schema +} + +// Fields of the User. +func (User) Fields() []ent.Field { + return []ent.Field{ + field.String("name"). + Default("Unknown"), + } +} + +// Edges of the User. +func (User) Edges() []ent.Edge { + return []ent.Edge{ + edge.To("liked_tweets", Tweet.Type). + Through("likes", TweetLike.Type), + edge.To("groups", Group.Type). + Through("joined_groups", UserGroup.Type), + edge.To("friends", User.Type). + Through("friendships", Friendship.Type), + edge.To("relatives", User.Type). + Through("relationship", Relationship.Type), + } +} diff --git a/entc/integration/edgeschema/ent/schema/usergroup.go b/entc/integration/edgeschema/ent/schema/usergroup.go new file mode 100644 index 0000000000..de3131dca7 --- /dev/null +++ b/entc/integration/edgeschema/ent/schema/usergroup.go @@ -0,0 +1,42 @@ +// 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" +) + +// UserGroup holds the schema definition for the UserGroup entity. +type UserGroup struct { + ent.Schema +} + +// Fields of the UserGroup. +func (UserGroup) Fields() []ent.Field { + return []ent.Field{ + field.Time("joined_at"). + Default(time.Now), + field.Int("user_id"), + field.Int("group_id"), + } +} + +// Edges of the UserGroup. +func (UserGroup) Edges() []ent.Edge { + return []ent.Edge{ + edge.To("user", User.Type). + Unique(). + Required(). + Field("user_id"), + edge.To("group", Group.Type). + Unique(). + Required(). + Field("group_id"), + } +} diff --git a/entc/integration/edgeschema/ent/tweet.go b/entc/integration/edgeschema/ent/tweet.go new file mode 100644 index 0000000000..955705cfcb --- /dev/null +++ b/entc/integration/edgeschema/ent/tweet.go @@ -0,0 +1,141 @@ +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "fmt" + "strings" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/entc/integration/edgeschema/ent/tweet" +) + +// Tweet is the model entity for the Tweet schema. +type Tweet struct { + config `json:"-"` + // ID of the ent. + ID int `json:"id,omitempty"` + // Text holds the value of the "text" field. + Text string `json:"text,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the TweetQuery when eager-loading is set. + Edges TweetEdges `json:"edges"` +} + +// TweetEdges holds the relations/edges for other nodes in the graph. +type TweetEdges struct { + // LikedUsers holds the value of the liked_users edge. + LikedUsers []*User `json:"liked_users,omitempty"` + // Likes holds the value of the likes edge. + Likes []*TweetLike `json:"likes,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [2]bool +} + +// LikedUsersOrErr returns the LikedUsers value or an error if the edge +// was not loaded in eager-loading. +func (e TweetEdges) LikedUsersOrErr() ([]*User, error) { + if e.loadedTypes[0] { + return e.LikedUsers, nil + } + return nil, &NotLoadedError{edge: "liked_users"} +} + +// 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[1] { + return e.Likes, nil + } + return nil, &NotLoadedError{edge: "likes"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*Tweet) scanValues(columns []string) ([]interface{}, error) { + values := make([]interface{}, len(columns)) + for i := range columns { + switch columns[i] { + case tweet.FieldID: + values[i] = new(sql.NullInt64) + case tweet.FieldText: + values[i] = new(sql.NullString) + default: + return nil, fmt.Errorf("unexpected column %q for type Tweet", columns[i]) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the Tweet fields. +func (t *Tweet) 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 tweet.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 tweet.FieldText: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field text", values[i]) + } else if value.Valid { + t.Text = value.String + } + } + } + return nil +} + +// QueryLikedUsers queries the "liked_users" edge of the Tweet entity. +func (t *Tweet) QueryLikedUsers() *UserQuery { + return (&TweetClient{config: t.config}).QueryLikedUsers(t) +} + +// QueryLikes queries the "likes" edge of the Tweet entity. +func (t *Tweet) QueryLikes() *TweetLikeQuery { + return (&TweetClient{config: t.config}).QueryLikes(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. +func (t *Tweet) Update() *TweetUpdateOne { + return (&TweetClient{config: t.config}).UpdateOne(t) +} + +// Unwrap unwraps the Tweet 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 *Tweet) Unwrap() *Tweet { + tx, ok := t.config.driver.(*txDriver) + if !ok { + panic("ent: Tweet is not a transactional entity") + } + t.config.driver = tx.drv + return t +} + +// String implements the fmt.Stringer. +func (t *Tweet) String() string { + var builder strings.Builder + builder.WriteString("Tweet(") + builder.WriteString(fmt.Sprintf("id=%v, ", t.ID)) + builder.WriteString("text=") + builder.WriteString(t.Text) + builder.WriteByte(')') + return builder.String() +} + +// Tweets is a parsable slice of Tweet. +type Tweets []*Tweet + +func (t Tweets) config(cfg config) { + for _i := range t { + t[_i].config = cfg + } +} diff --git a/entc/integration/edgeschema/ent/tweet/tweet.go b/entc/integration/edgeschema/ent/tweet/tweet.go new file mode 100644 index 0000000000..f91451b4c8 --- /dev/null +++ b/entc/integration/edgeschema/ent/tweet/tweet.go @@ -0,0 +1,52 @@ +// Code generated by entc, DO NOT EDIT. + +package tweet + +const ( + // Label holds the string label denoting the tweet type in the database. + Label = "tweet" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldText holds the string denoting the text field in the database. + FieldText = "text" + // EdgeLikedUsers holds the string denoting the liked_users edge name in mutations. + EdgeLikedUsers = "liked_users" + // EdgeLikes holds the string denoting the likes edge name in mutations. + EdgeLikes = "likes" + // 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. + LikedUsersTable = "tweet_likes" + // LikedUsersInverseTable is the table name for the User entity. + // It exists in this package in order to avoid circular dependency with the "user" package. + LikedUsersInverseTable = "users" + // LikesTable is the table that holds the likes relation/edge. + LikesTable = "tweet_likes" + // LikesInverseTable is the table name for the TweetLike entity. + // It exists in this package in order to avoid circular dependency with the "tweetlike" package. + LikesInverseTable = "tweet_likes" + // LikesColumn is the table column denoting the likes relation/edge. + LikesColumn = "tweet_id" +) + +// Columns holds all SQL columns for tweet fields. +var Columns = []string{ + FieldID, + FieldText, +} + +var ( + // LikedUsersPrimaryKey and LikedUsersColumn2 are the table columns denoting the + // primary key for the liked_users relation (M2M). + LikedUsersPrimaryKey = []string{"user_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/tweet/where.go b/entc/integration/edgeschema/ent/tweet/where.go new file mode 100644 index 0000000000..0ea7df8da8 --- /dev/null +++ b/entc/integration/edgeschema/ent/tweet/where.go @@ -0,0 +1,298 @@ +// Code generated by entc, DO NOT EDIT. + +package tweet + +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.Tweet { + return predicate.Tweet(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.Tweet { + return predicate.Tweet(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.Tweet { + return predicate.Tweet(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.Tweet { + return predicate.Tweet(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.Tweet { + return predicate.Tweet(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.Tweet { + return predicate.Tweet(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.Tweet { + return predicate.Tweet(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.Tweet { + return predicate.Tweet(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.Tweet { + return predicate.Tweet(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldID), id)) + }) +} + +// Text applies equality check predicate on the "text" field. It's identical to TextEQ. +func Text(v string) predicate.Tweet { + return predicate.Tweet(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldText), v)) + }) +} + +// TextEQ applies the EQ predicate on the "text" field. +func TextEQ(v string) predicate.Tweet { + return predicate.Tweet(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldText), v)) + }) +} + +// TextNEQ applies the NEQ predicate on the "text" field. +func TextNEQ(v string) predicate.Tweet { + return predicate.Tweet(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldText), v)) + }) +} + +// TextIn applies the In predicate on the "text" field. +func TextIn(vs ...string) predicate.Tweet { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Tweet(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(FieldText), v...)) + }) +} + +// TextNotIn applies the NotIn predicate on the "text" field. +func TextNotIn(vs ...string) predicate.Tweet { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Tweet(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(FieldText), v...)) + }) +} + +// TextGT applies the GT predicate on the "text" field. +func TextGT(v string) predicate.Tweet { + return predicate.Tweet(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldText), v)) + }) +} + +// TextGTE applies the GTE predicate on the "text" field. +func TextGTE(v string) predicate.Tweet { + return predicate.Tweet(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldText), v)) + }) +} + +// TextLT applies the LT predicate on the "text" field. +func TextLT(v string) predicate.Tweet { + return predicate.Tweet(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldText), v)) + }) +} + +// TextLTE applies the LTE predicate on the "text" field. +func TextLTE(v string) predicate.Tweet { + return predicate.Tweet(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldText), v)) + }) +} + +// TextContains applies the Contains predicate on the "text" field. +func TextContains(v string) predicate.Tweet { + return predicate.Tweet(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldText), v)) + }) +} + +// TextHasPrefix applies the HasPrefix predicate on the "text" field. +func TextHasPrefix(v string) predicate.Tweet { + return predicate.Tweet(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldText), v)) + }) +} + +// TextHasSuffix applies the HasSuffix predicate on the "text" field. +func TextHasSuffix(v string) predicate.Tweet { + return predicate.Tweet(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldText), v)) + }) +} + +// TextEqualFold applies the EqualFold predicate on the "text" field. +func TextEqualFold(v string) predicate.Tweet { + return predicate.Tweet(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldText), v)) + }) +} + +// TextContainsFold applies the ContainsFold predicate on the "text" field. +func TextContainsFold(v string) predicate.Tweet { + return predicate.Tweet(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldText), v)) + }) +} + +// HasLikedUsers applies the HasEdge predicate on the "liked_users" edge. +func HasLikedUsers() predicate.Tweet { + return predicate.Tweet(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(LikedUsersTable, FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, LikedUsersTable, LikedUsersPrimaryKey...), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasLikedUsersWith applies the HasEdge predicate on the "liked_users" edge with a given conditions (other predicates). +func HasLikedUsersWith(preds ...predicate.User) predicate.Tweet { + return predicate.Tweet(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(LikedUsersInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, LikedUsersTable, LikedUsersPrimaryKey...), + ) + 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) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(LikesTable, LikesColumn), + sqlgraph.Edge(sqlgraph.O2M, true, LikesTable, LikesColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasLikesWith applies the HasEdge predicate on the "likes" edge with a given conditions (other predicates). +func HasLikesWith(preds ...predicate.TweetLike) predicate.Tweet { + return predicate.Tweet(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(LikesInverseTable, LikesColumn), + sqlgraph.Edge(sqlgraph.O2M, true, LikesTable, LikesColumn), + ) + 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) { + 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.Tweet) predicate.Tweet { + return predicate.Tweet(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.Tweet) predicate.Tweet { + return predicate.Tweet(func(s *sql.Selector) { + p(s.Not()) + }) +} diff --git a/entc/integration/edgeschema/ent/tweet_create.go b/entc/integration/edgeschema/ent/tweet_create.go new file mode 100644 index 0000000000..ada9076f05 --- /dev/null +++ b/entc/integration/edgeschema/ent/tweet_create.go @@ -0,0 +1,265 @@ +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/edgeschema/ent/tweet" + "entgo.io/ent/entc/integration/edgeschema/ent/user" + "entgo.io/ent/schema/field" +) + +// TweetCreate is the builder for creating a Tweet entity. +type TweetCreate struct { + config + mutation *TweetMutation + hooks []Hook +} + +// SetText sets the "text" field. +func (tc *TweetCreate) SetText(s string) *TweetCreate { + tc.mutation.SetText(s) + return tc +} + +// AddLikedUserIDs adds the "liked_users" edge to the User entity by IDs. +func (tc *TweetCreate) AddLikedUserIDs(ids ...int) *TweetCreate { + tc.mutation.AddLikedUserIDs(ids...) + return tc +} + +// AddLikedUsers adds the "liked_users" edges to the User entity. +func (tc *TweetCreate) AddLikedUsers(u ...*User) *TweetCreate { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return tc.AddLikedUserIDs(ids...) +} + +// Mutation returns the TweetMutation object of the builder. +func (tc *TweetCreate) Mutation() *TweetMutation { + return tc.mutation +} + +// Save creates the Tweet in the database. +func (tc *TweetCreate) Save(ctx context.Context) (*Tweet, error) { + var ( + err error + node *Tweet + ) + 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.(*TweetMutation) + 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.(*Tweet) + if !ok { + return nil, fmt.Errorf("unexpected node type %T returned from TweetMutation", v) + } + node = nv + } + return node, err +} + +// SaveX calls Save and panics if Save returns an error. +func (tc *TweetCreate) SaveX(ctx context.Context) *Tweet { + v, err := tc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (tc *TweetCreate) Exec(ctx context.Context) error { + _, err := tc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (tc *TweetCreate) 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 *TweetCreate) check() error { + if _, ok := tc.mutation.Text(); !ok { + return &ValidationError{Name: "text", err: errors.New(`ent: missing required field "Tweet.text"`)} + } + return nil +} + +func (tc *TweetCreate) sqlSave(ctx context.Context) (*Tweet, error) { + _node, _spec := tc.createSpec() + if err := sqlgraph.CreateNode(ctx, tc.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return nil, err + } + id := _spec.ID.Value.(int64) + _node.ID = int(id) + return _node, nil +} + +func (tc *TweetCreate) createSpec() (*Tweet, *sqlgraph.CreateSpec) { + var ( + _node = &Tweet{config: tc.config} + _spec = &sqlgraph.CreateSpec{ + Table: tweet.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: tweet.FieldID, + }, + } + ) + if value, ok := tc.mutation.Text(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: tweet.FieldText, + }) + _node.Text = value + } + if nodes := tc.mutation.LikedUsersIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: tweet.LikedUsersTable, + Columns: tweet.LikedUsersPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + createE := &TweetLikeCreate{config: tc.config, mutation: newTweetLikeMutation(tc.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// TweetCreateBulk is the builder for creating many Tweet entities in bulk. +type TweetCreateBulk struct { + config + builders []*TweetCreate +} + +// Save creates the Tweet entities in the database. +func (tcb *TweetCreateBulk) Save(ctx context.Context) ([]*Tweet, error) { + specs := make([]*sqlgraph.CreateSpec, len(tcb.builders)) + nodes := make([]*Tweet, 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.(*TweetMutation) + 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{err.Error(), 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 *TweetCreateBulk) SaveX(ctx context.Context) []*Tweet { + v, err := tcb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (tcb *TweetCreateBulk) Exec(ctx context.Context) error { + _, err := tcb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (tcb *TweetCreateBulk) ExecX(ctx context.Context) { + if err := tcb.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/entc/integration/edgeschema/ent/tweet_delete.go b/entc/integration/edgeschema/ent/tweet_delete.go new file mode 100644 index 0000000000..1d745fac40 --- /dev/null +++ b/entc/integration/edgeschema/ent/tweet_delete.go @@ -0,0 +1,111 @@ +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "fmt" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/edgeschema/ent/predicate" + "entgo.io/ent/entc/integration/edgeschema/ent/tweet" + "entgo.io/ent/schema/field" +) + +// TweetDelete is the builder for deleting a Tweet entity. +type TweetDelete struct { + config + hooks []Hook + mutation *TweetMutation +} + +// Where appends a list predicates to the TweetDelete builder. +func (td *TweetDelete) Where(ps ...predicate.Tweet) *TweetDelete { + td.mutation.Where(ps...) + return td +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (td *TweetDelete) 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.(*TweetMutation) + 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 *TweetDelete) ExecX(ctx context.Context) int { + n, err := td.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (td *TweetDelete) sqlExec(ctx context.Context) (int, error) { + _spec := &sqlgraph.DeleteSpec{ + Node: &sqlgraph.NodeSpec{ + Table: tweet.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: tweet.FieldID, + }, + }, + } + if ps := td.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return sqlgraph.DeleteNodes(ctx, td.driver, _spec) +} + +// TweetDeleteOne is the builder for deleting a single Tweet entity. +type TweetDeleteOne struct { + td *TweetDelete +} + +// Exec executes the deletion query. +func (tdo *TweetDeleteOne) Exec(ctx context.Context) error { + n, err := tdo.td.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{tweet.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (tdo *TweetDeleteOne) ExecX(ctx context.Context) { + tdo.td.ExecX(ctx) +} diff --git a/entc/integration/edgeschema/ent/tweet_query.go b/entc/integration/edgeschema/ent/tweet_query.go new file mode 100644 index 0000000000..480110133e --- /dev/null +++ b/entc/integration/edgeschema/ent/tweet_query.go @@ -0,0 +1,686 @@ +// Code generated by entc, 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/tweet" + "entgo.io/ent/entc/integration/edgeschema/ent/tweetlike" + "entgo.io/ent/entc/integration/edgeschema/ent/user" + "entgo.io/ent/schema/field" +) + +// TweetQuery is the builder for querying Tweet entities. +type TweetQuery struct { + config + limit *int + offset *int + unique *bool + order []OrderFunc + fields []string + predicates []predicate.Tweet + // eager-loading edges. + withLikedUsers *UserQuery + withLikes *TweetLikeQuery + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the TweetQuery builder. +func (tq *TweetQuery) Where(ps ...predicate.Tweet) *TweetQuery { + tq.predicates = append(tq.predicates, ps...) + return tq +} + +// Limit adds a limit step to the query. +func (tq *TweetQuery) Limit(limit int) *TweetQuery { + tq.limit = &limit + return tq +} + +// Offset adds an offset step to the query. +func (tq *TweetQuery) Offset(offset int) *TweetQuery { + 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 *TweetQuery) Unique(unique bool) *TweetQuery { + tq.unique = &unique + return tq +} + +// Order adds an order step to the query. +func (tq *TweetQuery) Order(o ...OrderFunc) *TweetQuery { + tq.order = append(tq.order, o...) + return tq +} + +// QueryLikedUsers chains the current query on the "liked_users" edge. +func (tq *TweetQuery) QueryLikedUsers() *UserQuery { + query := &UserQuery{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(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, tweet.LikedUsersTable, tweet.LikedUsersPrimaryKey...), + ) + 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} + 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(tweetlike.Table, tweetlike.TweetColumn), + sqlgraph.Edge(sqlgraph.O2M, true, tweet.LikesTable, tweet.LikesColumn), + ) + 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) { + nodes, err := tq.Limit(1).All(ctx) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{tweet.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (tq *TweetQuery) FirstX(ctx context.Context) *Tweet { + node, err := tq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first Tweet ID from the query. +// Returns a *NotFoundError when no Tweet ID was found. +func (tq *TweetQuery) 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{tweet.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (tq *TweetQuery) FirstIDX(ctx context.Context) int { + id, err := tq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single Tweet entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Tweet entity is found. +// Returns a *NotFoundError when no Tweet entities are found. +func (tq *TweetQuery) Only(ctx context.Context) (*Tweet, 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{tweet.Label} + default: + return nil, &NotSingularError{tweet.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (tq *TweetQuery) OnlyX(ctx context.Context) *Tweet { + node, err := tq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only Tweet ID in the query. +// Returns a *NotSingularError when more than one Tweet ID is found. +// Returns a *NotFoundError when no entities are found. +func (tq *TweetQuery) 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{tweet.Label} + default: + err = &NotSingularError{tweet.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (tq *TweetQuery) 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 Tweets. +func (tq *TweetQuery) All(ctx context.Context) ([]*Tweet, 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 *TweetQuery) AllX(ctx context.Context) []*Tweet { + nodes, err := tq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of Tweet IDs. +func (tq *TweetQuery) IDs(ctx context.Context) ([]int, error) { + var ids []int + if err := tq.Select(tweet.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (tq *TweetQuery) 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 *TweetQuery) 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 *TweetQuery) 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 *TweetQuery) 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 *TweetQuery) ExistX(ctx context.Context) bool { + exist, err := tq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the TweetQuery 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 *TweetQuery) Clone() *TweetQuery { + if tq == nil { + return nil + } + return &TweetQuery{ + config: tq.config, + limit: tq.limit, + offset: tq.offset, + order: append([]OrderFunc{}, tq.order...), + predicates: append([]predicate.Tweet{}, tq.predicates...), + withLikedUsers: tq.withLikedUsers.Clone(), + withLikes: tq.withLikes.Clone(), + // clone intermediate query. + sql: tq.sql.Clone(), + path: tq.path, + unique: tq.unique, + } +} + +// WithLikedUsers tells the query-builder to eager-load the nodes that are connected to +// the "liked_users" edge. The optional arguments are used to configure the query builder of the edge. +func (tq *TweetQuery) WithLikedUsers(opts ...func(*UserQuery)) *TweetQuery { + query := &UserQuery{config: tq.config} + for _, opt := range opts { + opt(query) + } + tq.withLikedUsers = 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 { + query := &TweetLikeQuery{config: tq.config} + for _, opt := range opts { + opt(query) + } + tq.withLikes = 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 { +// Text string `json:"text,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.Tweet.Query(). +// GroupBy(tweet.FieldText). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +// +func (tq *TweetQuery) GroupBy(field string, fields ...string) *TweetGroupBy { + grbuild := &TweetGroupBy{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 = tweet.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 { +// Text string `json:"text,omitempty"` +// } +// +// client.Tweet.Query(). +// Select(tweet.FieldText). +// Scan(ctx, &v) +// +func (tq *TweetQuery) Select(fields ...string) *TweetSelect { + tq.fields = append(tq.fields, fields...) + selbuild := &TweetSelect{TweetQuery: tq} + selbuild.label = tweet.Label + selbuild.flds, selbuild.scan = &tq.fields, selbuild.Scan + return selbuild +} + +func (tq *TweetQuery) prepareQuery(ctx context.Context) error { + for _, f := range tq.fields { + if !tweet.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 *TweetQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Tweet, error) { + var ( + nodes = []*Tweet{} + _spec = tq.querySpec() + loadedTypes = [2]bool{ + tq.withLikedUsers != nil, + tq.withLikes != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]interface{}, error) { + return (*Tweet).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []interface{}) error { + node := &Tweet{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.withLikedUsers; 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.LikedUsers = []*User{} + } + query.Where(func(s *sql.Selector) { + joinT := sql.Table(tweet.LikedUsersTable) + s.Join(joinT).On(s.C(user.FieldID), joinT.C(tweet.LikedUsersPrimaryKey[0])) + s.Where(sql.InValues(joinT.C(tweet.LikedUsersPrimaryKey[1]), edgeids...)) + columns := s.SelectedColumns() + s.Select(joinT.C(tweet.LikedUsersPrimaryKey[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 "liked_users" node returned %v`, n.ID) + } + for kn := range nodes { + kn.Edges.LikedUsers = append(kn.Edges.LikedUsers, n) + } + } + } + + if query := tq.withLikes; 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.Likes = []*TweetLike{} + } + query.Where(predicate.TweetLike(func(s *sql.Selector) { + s.Where(sql.InValues(tweet.LikesColumn, 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) + } + node.Edges.Likes = append(node.Edges.Likes, n) + } + } + + return nodes, nil +} + +func (tq *TweetQuery) 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 *TweetQuery) 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 *TweetQuery) querySpec() *sqlgraph.QuerySpec { + _spec := &sqlgraph.QuerySpec{ + Node: &sqlgraph.NodeSpec{ + Table: tweet.Table, + Columns: tweet.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: tweet.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, tweet.FieldID) + for i := range fields { + if fields[i] != tweet.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 *TweetQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(tq.driver.Dialect()) + t1 := builder.Table(tweet.Table) + columns := tq.fields + if len(columns) == 0 { + columns = tweet.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 +} + +// TweetGroupBy is the group-by builder for Tweet entities. +type TweetGroupBy 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 *TweetGroupBy) Aggregate(fns ...AggregateFunc) *TweetGroupBy { + tgb.fns = append(tgb.fns, fns...) + return tgb +} + +// Scan applies the group-by query and scans the result into the given value. +func (tgb *TweetGroupBy) 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 *TweetGroupBy) sqlScan(ctx context.Context, v interface{}) error { + for _, f := range tgb.fields { + if !tweet.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 *TweetGroupBy) 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...)...) +} + +// TweetSelect is the builder for selecting fields of Tweet entities. +type TweetSelect struct { + *TweetQuery + 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 *TweetSelect) Scan(ctx context.Context, v interface{}) error { + if err := ts.prepareQuery(ctx); err != nil { + return err + } + ts.sql = ts.TweetQuery.sqlQuery(ctx) + return ts.sqlScan(ctx, v) +} + +func (ts *TweetSelect) 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/tweet_update.go b/entc/integration/edgeschema/ent/tweet_update.go new file mode 100644 index 0000000000..e0c60685a0 --- /dev/null +++ b/entc/integration/edgeschema/ent/tweet_update.go @@ -0,0 +1,476 @@ +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/edgeschema/ent/predicate" + "entgo.io/ent/entc/integration/edgeschema/ent/tweet" + "entgo.io/ent/entc/integration/edgeschema/ent/user" + "entgo.io/ent/schema/field" +) + +// TweetUpdate is the builder for updating Tweet entities. +type TweetUpdate struct { + config + hooks []Hook + mutation *TweetMutation +} + +// Where appends a list predicates to the TweetUpdate builder. +func (tu *TweetUpdate) Where(ps ...predicate.Tweet) *TweetUpdate { + tu.mutation.Where(ps...) + return tu +} + +// SetText sets the "text" field. +func (tu *TweetUpdate) SetText(s string) *TweetUpdate { + tu.mutation.SetText(s) + return tu +} + +// AddLikedUserIDs adds the "liked_users" edge to the User entity by IDs. +func (tu *TweetUpdate) AddLikedUserIDs(ids ...int) *TweetUpdate { + tu.mutation.AddLikedUserIDs(ids...) + return tu +} + +// AddLikedUsers adds the "liked_users" edges to the User entity. +func (tu *TweetUpdate) AddLikedUsers(u ...*User) *TweetUpdate { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return tu.AddLikedUserIDs(ids...) +} + +// Mutation returns the TweetMutation object of the builder. +func (tu *TweetUpdate) Mutation() *TweetMutation { + return tu.mutation +} + +// ClearLikedUsers clears all "liked_users" edges to the User entity. +func (tu *TweetUpdate) ClearLikedUsers() *TweetUpdate { + tu.mutation.ClearLikedUsers() + return tu +} + +// RemoveLikedUserIDs removes the "liked_users" edge to User entities by IDs. +func (tu *TweetUpdate) RemoveLikedUserIDs(ids ...int) *TweetUpdate { + tu.mutation.RemoveLikedUserIDs(ids...) + return tu +} + +// RemoveLikedUsers removes "liked_users" edges to User entities. +func (tu *TweetUpdate) RemoveLikedUsers(u ...*User) *TweetUpdate { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return tu.RemoveLikedUserIDs(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 ( + 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.(*TweetMutation) + 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 *TweetUpdate) SaveX(ctx context.Context) int { + affected, err := tu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (tu *TweetUpdate) Exec(ctx context.Context) error { + _, err := tu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (tu *TweetUpdate) ExecX(ctx context.Context) { + if err := tu.Exec(ctx); err != nil { + panic(err) + } +} + +func (tu *TweetUpdate) sqlSave(ctx context.Context) (n int, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: tweet.Table, + Columns: tweet.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: tweet.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.Text(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: tweet.FieldText, + }) + } + if tu.mutation.LikedUsersCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: tweet.LikedUsersTable, + Columns: tweet.LikedUsersPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + createE := &TweetLikeCreate{config: tu.config, mutation: newTweetLikeMutation(tu.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := tu.mutation.RemovedLikedUsersIDs(); len(nodes) > 0 && !tu.mutation.LikedUsersCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: tweet.LikedUsersTable, + Columns: tweet.LikedUsersPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + createE := &TweetLikeCreate{config: tu.config, mutation: newTweetLikeMutation(tu.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := tu.mutation.LikedUsersIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: tweet.LikedUsersTable, + Columns: tweet.LikedUsersPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + createE := &TweetLikeCreate{config: tu.config, mutation: newTweetLikeMutation(tu.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _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} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return 0, err + } + return n, nil +} + +// TweetUpdateOne is the builder for updating a single Tweet entity. +type TweetUpdateOne struct { + config + fields []string + hooks []Hook + mutation *TweetMutation +} + +// SetText sets the "text" field. +func (tuo *TweetUpdateOne) SetText(s string) *TweetUpdateOne { + tuo.mutation.SetText(s) + return tuo +} + +// AddLikedUserIDs adds the "liked_users" edge to the User entity by IDs. +func (tuo *TweetUpdateOne) AddLikedUserIDs(ids ...int) *TweetUpdateOne { + tuo.mutation.AddLikedUserIDs(ids...) + return tuo +} + +// AddLikedUsers adds the "liked_users" edges to the User entity. +func (tuo *TweetUpdateOne) AddLikedUsers(u ...*User) *TweetUpdateOne { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return tuo.AddLikedUserIDs(ids...) +} + +// Mutation returns the TweetMutation object of the builder. +func (tuo *TweetUpdateOne) Mutation() *TweetMutation { + return tuo.mutation +} + +// ClearLikedUsers clears all "liked_users" edges to the User entity. +func (tuo *TweetUpdateOne) ClearLikedUsers() *TweetUpdateOne { + tuo.mutation.ClearLikedUsers() + return tuo +} + +// RemoveLikedUserIDs removes the "liked_users" edge to User entities by IDs. +func (tuo *TweetUpdateOne) RemoveLikedUserIDs(ids ...int) *TweetUpdateOne { + tuo.mutation.RemoveLikedUserIDs(ids...) + return tuo +} + +// RemoveLikedUsers removes "liked_users" edges to User entities. +func (tuo *TweetUpdateOne) RemoveLikedUsers(u ...*User) *TweetUpdateOne { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return tuo.RemoveLikedUserIDs(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 { + tuo.fields = append([]string{field}, fields...) + return tuo +} + +// Save executes the query and returns the updated Tweet entity. +func (tuo *TweetUpdateOne) Save(ctx context.Context) (*Tweet, error) { + var ( + err error + node *Tweet + ) + 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.(*TweetMutation) + 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.(*Tweet) + if !ok { + return nil, fmt.Errorf("unexpected node type %T returned from TweetMutation", v) + } + node = nv + } + return node, err +} + +// SaveX is like Save, but panics if an error occurs. +func (tuo *TweetUpdateOne) SaveX(ctx context.Context) *Tweet { + node, err := tuo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (tuo *TweetUpdateOne) Exec(ctx context.Context) error { + _, err := tuo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (tuo *TweetUpdateOne) ExecX(ctx context.Context) { + if err := tuo.Exec(ctx); err != nil { + panic(err) + } +} + +func (tuo *TweetUpdateOne) sqlSave(ctx context.Context) (_node *Tweet, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: tweet.Table, + Columns: tweet.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: tweet.FieldID, + }, + }, + } + id, ok := tuo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Tweet.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, tweet.FieldID) + for _, f := range fields { + if !tweet.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != tweet.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.Text(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: tweet.FieldText, + }) + } + if tuo.mutation.LikedUsersCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: tweet.LikedUsersTable, + Columns: tweet.LikedUsersPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + createE := &TweetLikeCreate{config: tuo.config, mutation: newTweetLikeMutation(tuo.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := tuo.mutation.RemovedLikedUsersIDs(); len(nodes) > 0 && !tuo.mutation.LikedUsersCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: tweet.LikedUsersTable, + Columns: tweet.LikedUsersPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + createE := &TweetLikeCreate{config: tuo.config, mutation: newTweetLikeMutation(tuo.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := tuo.mutation.LikedUsersIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: tweet.LikedUsersTable, + Columns: tweet.LikedUsersPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + createE := &TweetLikeCreate{config: tuo.config, mutation: newTweetLikeMutation(tuo.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &Tweet{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{tweet.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return nil, err + } + return _node, nil +} diff --git a/entc/integration/edgeschema/ent/tweetlike.go b/entc/integration/edgeschema/ent/tweetlike.go new file mode 100644 index 0000000000..219416b8ca --- /dev/null +++ b/entc/integration/edgeschema/ent/tweetlike.go @@ -0,0 +1,167 @@ +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "fmt" + "strings" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/entc/integration/edgeschema/ent/tweet" + "entgo.io/ent/entc/integration/edgeschema/ent/tweetlike" + "entgo.io/ent/entc/integration/edgeschema/ent/user" +) + +// TweetLike is the model entity for the TweetLike schema. +type TweetLike struct { + config `json:"-"` + // LikedAt holds the value of the "liked_at" field. + LikedAt time.Time `json:"liked_at,omitempty"` + // UserID holds the value of the "user_id" field. + UserID int `json:"user_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 TweetLikeQuery when eager-loading is set. + Edges TweetLikeEdges `json:"edges"` +} + +// TweetLikeEdges holds the relations/edges for other nodes in the graph. +type TweetLikeEdges struct { + // User holds the value of the user edge. + User *User `json:"user,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 +} + +// UserOrErr returns the User value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e TweetLikeEdges) UserOrErr() (*User, error) { + if e.loadedTypes[0] { + if e.User == nil { + // The edge user was loaded in eager-loading, + // but was not found. + return nil, &NotFoundError{label: user.Label} + } + return e.User, nil + } + return nil, &NotLoadedError{edge: "user"} +} + +// 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 TweetLikeEdges) 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 (*TweetLike) scanValues(columns []string) ([]interface{}, error) { + values := make([]interface{}, len(columns)) + for i := range columns { + switch columns[i] { + case tweetlike.FieldUserID, tweetlike.FieldTweetID: + values[i] = new(sql.NullInt64) + case tweetlike.FieldLikedAt: + values[i] = new(sql.NullTime) + default: + return nil, fmt.Errorf("unexpected column %q for type TweetLike", columns[i]) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the TweetLike fields. +func (tl *TweetLike) 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 tweetlike.FieldLikedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field liked_at", values[i]) + } else if value.Valid { + tl.LikedAt = value.Time + } + case tweetlike.FieldUserID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field user_id", values[i]) + } else if value.Valid { + tl.UserID = int(value.Int64) + } + case tweetlike.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 { + tl.TweetID = int(value.Int64) + } + } + } + return nil +} + +// QueryUser queries the "user" edge of the TweetLike entity. +func (tl *TweetLike) QueryUser() *UserQuery { + return (&TweetLikeClient{config: tl.config}).QueryUser(tl) +} + +// QueryTweet queries the "tweet" edge of the TweetLike entity. +func (tl *TweetLike) QueryTweet() *TweetQuery { + return (&TweetLikeClient{config: tl.config}).QueryTweet(tl) +} + +// Update returns a builder for updating this TweetLike. +// Note that you need to call TweetLike.Unwrap() before calling this method if this TweetLike +// was returned from a transaction, and the transaction was committed or rolled back. +func (tl *TweetLike) Update() *TweetLikeUpdateOne { + return (&TweetLikeClient{config: tl.config}).UpdateOne(tl) +} + +// Unwrap unwraps the TweetLike 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 (tl *TweetLike) Unwrap() *TweetLike { + tx, ok := tl.config.driver.(*txDriver) + if !ok { + panic("ent: TweetLike is not a transactional entity") + } + tl.config.driver = tx.drv + return tl +} + +// String implements the fmt.Stringer. +func (tl *TweetLike) String() string { + var builder strings.Builder + builder.WriteString("TweetLike(") + builder.WriteString("liked_at=") + builder.WriteString(tl.LikedAt.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("user_id=") + builder.WriteString(fmt.Sprintf("%v", tl.UserID)) + builder.WriteString(", ") + builder.WriteString("tweet_id=") + builder.WriteString(fmt.Sprintf("%v", tl.TweetID)) + builder.WriteByte(')') + return builder.String() +} + +// TweetLikes is a parsable slice of TweetLike. +type TweetLikes []*TweetLike + +func (tl TweetLikes) config(cfg config) { + for _i := range tl { + tl[_i].config = cfg + } +} diff --git a/entc/integration/edgeschema/ent/tweetlike/tweetlike.go b/entc/integration/edgeschema/ent/tweetlike/tweetlike.go new file mode 100644 index 0000000000..e149b55823 --- /dev/null +++ b/entc/integration/edgeschema/ent/tweetlike/tweetlike.go @@ -0,0 +1,64 @@ +// Code generated by entc, DO NOT EDIT. + +package tweetlike + +import ( + "time" +) + +const ( + // Label holds the string label denoting the tweetlike type in the database. + Label = "tweet_like" + // FieldLikedAt holds the string denoting the liked_at field in the database. + FieldLikedAt = "liked_at" + // FieldUserID holds the string denoting the user_id field in the database. + FieldUserID = "user_id" + // FieldTweetID holds the string denoting the tweet_id field in the database. + FieldTweetID = "tweet_id" + // EdgeUser holds the string denoting the user edge name in mutations. + EdgeUser = "user" + // EdgeTweet holds the string denoting the tweet edge name in mutations. + EdgeTweet = "tweet" + // UserFieldID holds the string denoting the ID field of the User. + UserFieldID = "id" + // TweetFieldID holds the string denoting the ID field of the Tweet. + TweetFieldID = "id" + // Table holds the table name of the tweetlike in the database. + Table = "tweet_likes" + // UserTable is the table that holds the user relation/edge. + UserTable = "tweet_likes" + // 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" + // UserColumn is the table column denoting the user relation/edge. + UserColumn = "user_id" + // TweetTable is the table that holds the tweet relation/edge. + TweetTable = "tweet_likes" + // 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 tweetlike fields. +var Columns = []string{ + FieldLikedAt, + FieldUserID, + 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 ( + // DefaultLikedAt holds the default value on creation for the "liked_at" field. + DefaultLikedAt func() time.Time +) diff --git a/entc/integration/edgeschema/ent/tweetlike/where.go b/entc/integration/edgeschema/ent/tweetlike/where.go new file mode 100644 index 0000000000..c8e62d6c7d --- /dev/null +++ b/entc/integration/edgeschema/ent/tweetlike/where.go @@ -0,0 +1,292 @@ +// Code generated by entc, DO NOT EDIT. + +package tweetlike + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/edgeschema/ent/predicate" +) + +// LikedAt applies equality check predicate on the "liked_at" field. It's identical to LikedAtEQ. +func LikedAt(v time.Time) predicate.TweetLike { + return predicate.TweetLike(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldLikedAt), v)) + }) +} + +// UserID applies equality check predicate on the "user_id" field. It's identical to UserIDEQ. +func UserID(v int) predicate.TweetLike { + return predicate.TweetLike(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldUserID), v)) + }) +} + +// TweetID applies equality check predicate on the "tweet_id" field. It's identical to TweetIDEQ. +func TweetID(v int) predicate.TweetLike { + return predicate.TweetLike(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldTweetID), v)) + }) +} + +// LikedAtEQ applies the EQ predicate on the "liked_at" field. +func LikedAtEQ(v time.Time) predicate.TweetLike { + return predicate.TweetLike(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldLikedAt), v)) + }) +} + +// LikedAtNEQ applies the NEQ predicate on the "liked_at" field. +func LikedAtNEQ(v time.Time) predicate.TweetLike { + return predicate.TweetLike(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldLikedAt), v)) + }) +} + +// LikedAtIn applies the In predicate on the "liked_at" field. +func LikedAtIn(vs ...time.Time) predicate.TweetLike { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.TweetLike(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(FieldLikedAt), v...)) + }) +} + +// LikedAtNotIn applies the NotIn predicate on the "liked_at" field. +func LikedAtNotIn(vs ...time.Time) predicate.TweetLike { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.TweetLike(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(FieldLikedAt), v...)) + }) +} + +// LikedAtGT applies the GT predicate on the "liked_at" field. +func LikedAtGT(v time.Time) predicate.TweetLike { + return predicate.TweetLike(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldLikedAt), v)) + }) +} + +// LikedAtGTE applies the GTE predicate on the "liked_at" field. +func LikedAtGTE(v time.Time) predicate.TweetLike { + return predicate.TweetLike(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldLikedAt), v)) + }) +} + +// LikedAtLT applies the LT predicate on the "liked_at" field. +func LikedAtLT(v time.Time) predicate.TweetLike { + return predicate.TweetLike(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldLikedAt), v)) + }) +} + +// LikedAtLTE applies the LTE predicate on the "liked_at" field. +func LikedAtLTE(v time.Time) predicate.TweetLike { + return predicate.TweetLike(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldLikedAt), v)) + }) +} + +// UserIDEQ applies the EQ predicate on the "user_id" field. +func UserIDEQ(v int) predicate.TweetLike { + return predicate.TweetLike(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldUserID), v)) + }) +} + +// UserIDNEQ applies the NEQ predicate on the "user_id" field. +func UserIDNEQ(v int) predicate.TweetLike { + return predicate.TweetLike(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldUserID), v)) + }) +} + +// UserIDIn applies the In predicate on the "user_id" field. +func UserIDIn(vs ...int) predicate.TweetLike { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.TweetLike(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(FieldUserID), v...)) + }) +} + +// UserIDNotIn applies the NotIn predicate on the "user_id" field. +func UserIDNotIn(vs ...int) predicate.TweetLike { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.TweetLike(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(FieldUserID), v...)) + }) +} + +// TweetIDEQ applies the EQ predicate on the "tweet_id" field. +func TweetIDEQ(v int) predicate.TweetLike { + return predicate.TweetLike(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.TweetLike { + return predicate.TweetLike(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.TweetLike { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.TweetLike(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.TweetLike { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.TweetLike(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...)) + }) +} + +// HasUser applies the HasEdge predicate on the "user" edge. +func HasUser() predicate.TweetLike { + return predicate.TweetLike(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, UserColumn), + sqlgraph.To(UserInverseTable, UserFieldID), + sqlgraph.Edge(sqlgraph.M2O, false, UserTable, UserColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasUserWith applies the HasEdge predicate on the "user" edge with a given conditions (other predicates). +func HasUserWith(preds ...predicate.User) predicate.TweetLike { + return predicate.TweetLike(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, UserColumn), + sqlgraph.To(UserInverseTable, UserFieldID), + sqlgraph.Edge(sqlgraph.M2O, false, UserTable, UserColumn), + ) + 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.TweetLike { + return predicate.TweetLike(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, TweetColumn), + sqlgraph.To(TweetInverseTable, TweetFieldID), + 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.TweetLike { + return predicate.TweetLike(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, TweetColumn), + sqlgraph.To(TweetInverseTable, TweetFieldID), + 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.TweetLike) predicate.TweetLike { + return predicate.TweetLike(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.TweetLike) predicate.TweetLike { + return predicate.TweetLike(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.TweetLike) predicate.TweetLike { + return predicate.TweetLike(func(s *sql.Selector) { + p(s.Not()) + }) +} diff --git a/entc/integration/edgeschema/ent/tweetlike_create.go b/entc/integration/edgeschema/ent/tweetlike_create.go new file mode 100644 index 0000000000..2fc3fb3ad7 --- /dev/null +++ b/entc/integration/edgeschema/ent/tweetlike_create.go @@ -0,0 +1,308 @@ +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/edgeschema/ent/tweet" + "entgo.io/ent/entc/integration/edgeschema/ent/tweetlike" + "entgo.io/ent/entc/integration/edgeschema/ent/user" + "entgo.io/ent/schema/field" +) + +// TweetLikeCreate is the builder for creating a TweetLike entity. +type TweetLikeCreate struct { + config + mutation *TweetLikeMutation + hooks []Hook +} + +// SetLikedAt sets the "liked_at" field. +func (tlc *TweetLikeCreate) SetLikedAt(t time.Time) *TweetLikeCreate { + tlc.mutation.SetLikedAt(t) + return tlc +} + +// SetNillableLikedAt sets the "liked_at" field if the given value is not nil. +func (tlc *TweetLikeCreate) SetNillableLikedAt(t *time.Time) *TweetLikeCreate { + if t != nil { + tlc.SetLikedAt(*t) + } + return tlc +} + +// SetUserID sets the "user_id" field. +func (tlc *TweetLikeCreate) SetUserID(i int) *TweetLikeCreate { + tlc.mutation.SetUserID(i) + return tlc +} + +// SetTweetID sets the "tweet_id" field. +func (tlc *TweetLikeCreate) SetTweetID(i int) *TweetLikeCreate { + tlc.mutation.SetTweetID(i) + return tlc +} + +// SetUser sets the "user" edge to the User entity. +func (tlc *TweetLikeCreate) SetUser(u *User) *TweetLikeCreate { + return tlc.SetUserID(u.ID) +} + +// SetTweet sets the "tweet" edge to the Tweet entity. +func (tlc *TweetLikeCreate) SetTweet(t *Tweet) *TweetLikeCreate { + return tlc.SetTweetID(t.ID) +} + +// Mutation returns the TweetLikeMutation object of the builder. +func (tlc *TweetLikeCreate) Mutation() *TweetLikeMutation { + return tlc.mutation +} + +// Save creates the TweetLike in the database. +func (tlc *TweetLikeCreate) Save(ctx context.Context) (*TweetLike, error) { + var ( + err error + node *TweetLike + ) + tlc.defaults() + if len(tlc.hooks) == 0 { + if err = tlc.check(); err != nil { + return nil, err + } + node, err = tlc.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*TweetLikeMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err = tlc.check(); err != nil { + return nil, err + } + tlc.mutation = mutation + if node, err = tlc.sqlSave(ctx); err != nil { + return nil, err + } + return node, err + }) + for i := len(tlc.hooks) - 1; i >= 0; i-- { + if tlc.hooks[i] == nil { + return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = tlc.hooks[i](mut) + } + v, err := mut.Mutate(ctx, tlc.mutation) + if err != nil { + return nil, err + } + nv, ok := v.(*TweetLike) + if !ok { + return nil, fmt.Errorf("unexpected node type %T returned from TweetLikeMutation", v) + } + node = nv + } + return node, err +} + +// SaveX calls Save and panics if Save returns an error. +func (tlc *TweetLikeCreate) SaveX(ctx context.Context) *TweetLike { + v, err := tlc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (tlc *TweetLikeCreate) Exec(ctx context.Context) error { + _, err := tlc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (tlc *TweetLikeCreate) ExecX(ctx context.Context) { + if err := tlc.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (tlc *TweetLikeCreate) defaults() { + if _, ok := tlc.mutation.LikedAt(); !ok { + v := tweetlike.DefaultLikedAt() + tlc.mutation.SetLikedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (tlc *TweetLikeCreate) check() error { + if _, ok := tlc.mutation.LikedAt(); !ok { + return &ValidationError{Name: "liked_at", err: errors.New(`ent: missing required field "TweetLike.liked_at"`)} + } + if _, ok := tlc.mutation.UserID(); !ok { + return &ValidationError{Name: "user_id", err: errors.New(`ent: missing required field "TweetLike.user_id"`)} + } + if _, ok := tlc.mutation.TweetID(); !ok { + return &ValidationError{Name: "tweet_id", err: errors.New(`ent: missing required field "TweetLike.tweet_id"`)} + } + if _, ok := tlc.mutation.UserID(); !ok { + return &ValidationError{Name: "user", err: errors.New(`ent: missing required edge "TweetLike.user"`)} + } + if _, ok := tlc.mutation.TweetID(); !ok { + return &ValidationError{Name: "tweet", err: errors.New(`ent: missing required edge "TweetLike.tweet"`)} + } + return nil +} + +func (tlc *TweetLikeCreate) sqlSave(ctx context.Context) (*TweetLike, error) { + _node, _spec := tlc.createSpec() + if err := sqlgraph.CreateNode(ctx, tlc.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return nil, err + } + return _node, nil +} + +func (tlc *TweetLikeCreate) createSpec() (*TweetLike, *sqlgraph.CreateSpec) { + var ( + _node = &TweetLike{config: tlc.config} + _spec = &sqlgraph.CreateSpec{ + Table: tweetlike.Table, + } + ) + if value, ok := tlc.mutation.LikedAt(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: tweetlike.FieldLikedAt, + }) + _node.LikedAt = value + } + if nodes := tlc.mutation.UserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: tweetlike.UserTable, + Columns: []string{tweetlike.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.UserID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := tlc.mutation.TweetIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: tweetlike.TweetTable, + Columns: []string{tweetlike.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 +} + +// TweetLikeCreateBulk is the builder for creating many TweetLike entities in bulk. +type TweetLikeCreateBulk struct { + config + builders []*TweetLikeCreate +} + +// Save creates the TweetLike entities in the database. +func (tlcb *TweetLikeCreateBulk) Save(ctx context.Context) ([]*TweetLike, error) { + specs := make([]*sqlgraph.CreateSpec, len(tlcb.builders)) + nodes := make([]*TweetLike, len(tlcb.builders)) + mutators := make([]Mutator, len(tlcb.builders)) + for i := range tlcb.builders { + func(i int, root context.Context) { + builder := tlcb.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*TweetLikeMutation) + 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, tlcb.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, tlcb.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + } + } + if err != nil { + return nil, err + } + mutation.done = true + return nodes[i], nil + }) + for i := len(builder.hooks) - 1; i >= 0; i-- { + mut = builder.hooks[i](mut) + } + mutators[i] = mut + }(i, ctx) + } + if len(mutators) > 0 { + if _, err := mutators[0].Mutate(ctx, tlcb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (tlcb *TweetLikeCreateBulk) SaveX(ctx context.Context) []*TweetLike { + v, err := tlcb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (tlcb *TweetLikeCreateBulk) Exec(ctx context.Context) error { + _, err := tlcb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (tlcb *TweetLikeCreateBulk) ExecX(ctx context.Context) { + if err := tlcb.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/entc/integration/edgeschema/ent/tweetlike_delete.go b/entc/integration/edgeschema/ent/tweetlike_delete.go new file mode 100644 index 0000000000..68457ea282 --- /dev/null +++ b/entc/integration/edgeschema/ent/tweetlike_delete.go @@ -0,0 +1,106 @@ +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "fmt" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/edgeschema/ent/predicate" + "entgo.io/ent/entc/integration/edgeschema/ent/tweetlike" +) + +// TweetLikeDelete is the builder for deleting a TweetLike entity. +type TweetLikeDelete struct { + config + hooks []Hook + mutation *TweetLikeMutation +} + +// Where appends a list predicates to the TweetLikeDelete builder. +func (tld *TweetLikeDelete) Where(ps ...predicate.TweetLike) *TweetLikeDelete { + tld.mutation.Where(ps...) + return tld +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (tld *TweetLikeDelete) Exec(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(tld.hooks) == 0 { + affected, err = tld.sqlExec(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*TweetLikeMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + tld.mutation = mutation + affected, err = tld.sqlExec(ctx) + mutation.done = true + return affected, err + }) + for i := len(tld.hooks) - 1; i >= 0; i-- { + if tld.hooks[i] == nil { + return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = tld.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, tld.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// ExecX is like Exec, but panics if an error occurs. +func (tld *TweetLikeDelete) ExecX(ctx context.Context) int { + n, err := tld.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (tld *TweetLikeDelete) sqlExec(ctx context.Context) (int, error) { + _spec := &sqlgraph.DeleteSpec{ + Node: &sqlgraph.NodeSpec{ + Table: tweetlike.Table, + }, + } + if ps := tld.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return sqlgraph.DeleteNodes(ctx, tld.driver, _spec) +} + +// TweetLikeDeleteOne is the builder for deleting a single TweetLike entity. +type TweetLikeDeleteOne struct { + tld *TweetLikeDelete +} + +// Exec executes the deletion query. +func (tldo *TweetLikeDeleteOne) Exec(ctx context.Context) error { + n, err := tldo.tld.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{tweetlike.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (tldo *TweetLikeDeleteOne) ExecX(ctx context.Context) { + tldo.tld.ExecX(ctx) +} diff --git a/entc/integration/edgeschema/ent/tweetlike_query.go b/entc/integration/edgeschema/ent/tweetlike_query.go new file mode 100644 index 0000000000..28a5775608 --- /dev/null +++ b/entc/integration/edgeschema/ent/tweetlike_query.go @@ -0,0 +1,580 @@ +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "fmt" + "math" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/edgeschema/ent/predicate" + "entgo.io/ent/entc/integration/edgeschema/ent/tweet" + "entgo.io/ent/entc/integration/edgeschema/ent/tweetlike" + "entgo.io/ent/entc/integration/edgeschema/ent/user" +) + +// TweetLikeQuery is the builder for querying TweetLike entities. +type TweetLikeQuery struct { + config + limit *int + offset *int + unique *bool + order []OrderFunc + fields []string + predicates []predicate.TweetLike + // eager-loading edges. + withUser *UserQuery + 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 TweetLikeQuery builder. +func (tlq *TweetLikeQuery) Where(ps ...predicate.TweetLike) *TweetLikeQuery { + tlq.predicates = append(tlq.predicates, ps...) + return tlq +} + +// Limit adds a limit step to the query. +func (tlq *TweetLikeQuery) Limit(limit int) *TweetLikeQuery { + tlq.limit = &limit + return tlq +} + +// Offset adds an offset step to the query. +func (tlq *TweetLikeQuery) Offset(offset int) *TweetLikeQuery { + tlq.offset = &offset + return tlq +} + +// 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 (tlq *TweetLikeQuery) Unique(unique bool) *TweetLikeQuery { + tlq.unique = &unique + return tlq +} + +// Order adds an order step to the query. +func (tlq *TweetLikeQuery) Order(o ...OrderFunc) *TweetLikeQuery { + tlq.order = append(tlq.order, o...) + return tlq +} + +// QueryUser chains the current query on the "user" edge. +func (tlq *TweetLikeQuery) QueryUser() *UserQuery { + query := &UserQuery{config: tlq.config} + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := tlq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := tlq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(tweetlike.Table, tweetlike.UserColumn, selector), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, tweetlike.UserTable, tweetlike.UserColumn), + ) + fromU = sqlgraph.SetNeighbors(tlq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryTweet chains the current query on the "tweet" edge. +func (tlq *TweetLikeQuery) QueryTweet() *TweetQuery { + query := &TweetQuery{config: tlq.config} + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := tlq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := tlq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(tweetlike.Table, tweetlike.TweetColumn, selector), + sqlgraph.To(tweet.Table, tweet.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, tweetlike.TweetTable, tweetlike.TweetColumn), + ) + fromU = sqlgraph.SetNeighbors(tlq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first TweetLike entity from the query. +// Returns a *NotFoundError when no TweetLike was found. +func (tlq *TweetLikeQuery) First(ctx context.Context) (*TweetLike, error) { + nodes, err := tlq.Limit(1).All(ctx) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{tweetlike.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (tlq *TweetLikeQuery) FirstX(ctx context.Context) *TweetLike { + node, err := tlq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// Only returns a single TweetLike entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one TweetLike entity is found. +// Returns a *NotFoundError when no TweetLike entities are found. +func (tlq *TweetLikeQuery) Only(ctx context.Context) (*TweetLike, error) { + nodes, err := tlq.Limit(2).All(ctx) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{tweetlike.Label} + default: + return nil, &NotSingularError{tweetlike.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (tlq *TweetLikeQuery) OnlyX(ctx context.Context) *TweetLike { + node, err := tlq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// All executes the query and returns a list of TweetLikes. +func (tlq *TweetLikeQuery) All(ctx context.Context) ([]*TweetLike, error) { + if err := tlq.prepareQuery(ctx); err != nil { + return nil, err + } + return tlq.sqlAll(ctx) +} + +// AllX is like All, but panics if an error occurs. +func (tlq *TweetLikeQuery) AllX(ctx context.Context) []*TweetLike { + nodes, err := tlq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// Count returns the count of the given query. +func (tlq *TweetLikeQuery) Count(ctx context.Context) (int, error) { + if err := tlq.prepareQuery(ctx); err != nil { + return 0, err + } + return tlq.sqlCount(ctx) +} + +// CountX is like Count, but panics if an error occurs. +func (tlq *TweetLikeQuery) CountX(ctx context.Context) int { + count, err := tlq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (tlq *TweetLikeQuery) Exist(ctx context.Context) (bool, error) { + if err := tlq.prepareQuery(ctx); err != nil { + return false, err + } + return tlq.sqlExist(ctx) +} + +// ExistX is like Exist, but panics if an error occurs. +func (tlq *TweetLikeQuery) ExistX(ctx context.Context) bool { + exist, err := tlq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the TweetLikeQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (tlq *TweetLikeQuery) Clone() *TweetLikeQuery { + if tlq == nil { + return nil + } + return &TweetLikeQuery{ + config: tlq.config, + limit: tlq.limit, + offset: tlq.offset, + order: append([]OrderFunc{}, tlq.order...), + predicates: append([]predicate.TweetLike{}, tlq.predicates...), + withUser: tlq.withUser.Clone(), + withTweet: tlq.withTweet.Clone(), + // clone intermediate query. + sql: tlq.sql.Clone(), + path: tlq.path, + unique: tlq.unique, + } +} + +// WithUser tells the query-builder to eager-load the nodes that are connected to +// the "user" edge. The optional arguments are used to configure the query builder of the edge. +func (tlq *TweetLikeQuery) WithUser(opts ...func(*UserQuery)) *TweetLikeQuery { + query := &UserQuery{config: tlq.config} + for _, opt := range opts { + opt(query) + } + tlq.withUser = query + return tlq +} + +// 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 (tlq *TweetLikeQuery) WithTweet(opts ...func(*TweetQuery)) *TweetLikeQuery { + query := &TweetQuery{config: tlq.config} + for _, opt := range opts { + opt(query) + } + tlq.withTweet = query + return tlq +} + +// 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 { +// LikedAt time.Time `json:"liked_at,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.TweetLike.Query(). +// GroupBy(tweetlike.FieldLikedAt). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +// +func (tlq *TweetLikeQuery) GroupBy(field string, fields ...string) *TweetLikeGroupBy { + grbuild := &TweetLikeGroupBy{config: tlq.config} + grbuild.fields = append([]string{field}, fields...) + grbuild.path = func(ctx context.Context) (prev *sql.Selector, err error) { + if err := tlq.prepareQuery(ctx); err != nil { + return nil, err + } + return tlq.sqlQuery(ctx), nil + } + grbuild.label = tweetlike.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 { +// LikedAt time.Time `json:"liked_at,omitempty"` +// } +// +// client.TweetLike.Query(). +// Select(tweetlike.FieldLikedAt). +// Scan(ctx, &v) +// +func (tlq *TweetLikeQuery) Select(fields ...string) *TweetLikeSelect { + tlq.fields = append(tlq.fields, fields...) + selbuild := &TweetLikeSelect{TweetLikeQuery: tlq} + selbuild.label = tweetlike.Label + selbuild.flds, selbuild.scan = &tlq.fields, selbuild.Scan + return selbuild +} + +func (tlq *TweetLikeQuery) prepareQuery(ctx context.Context) error { + for _, f := range tlq.fields { + if !tweetlike.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if tlq.path != nil { + prev, err := tlq.path(ctx) + if err != nil { + return err + } + tlq.sql = prev + } + return nil +} + +func (tlq *TweetLikeQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*TweetLike, error) { + var ( + nodes = []*TweetLike{} + _spec = tlq.querySpec() + loadedTypes = [2]bool{ + tlq.withUser != nil, + tlq.withTweet != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]interface{}, error) { + return (*TweetLike).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []interface{}) error { + node := &TweetLike{config: tlq.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, tlq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + + if query := tlq.withUser; query != nil { + ids := make([]int, 0, len(nodes)) + nodeids := make(map[int][]*TweetLike) + for i := range nodes { + fk := nodes[i].UserID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + query.Where(user.IDIn(ids...)) + neighbors, err := query.All(ctx) + if err != nil { + return nil, err + } + for _, n := range neighbors { + nodes, ok := nodeids[n.ID] + if !ok { + return nil, fmt.Errorf(`unexpected foreign-key "user_id" returned %v`, n.ID) + } + for i := range nodes { + nodes[i].Edges.User = n + } + } + } + + if query := tlq.withTweet; query != nil { + ids := make([]int, 0, len(nodes)) + nodeids := make(map[int][]*TweetLike) + 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 (tlq *TweetLikeQuery) sqlCount(ctx context.Context) (int, error) { + _spec := tlq.querySpec() + _spec.Unique = false + _spec.Node.Columns = nil + return sqlgraph.CountNodes(ctx, tlq.driver, _spec) +} + +func (tlq *TweetLikeQuery) sqlExist(ctx context.Context) (bool, error) { + n, err := tlq.sqlCount(ctx) + if err != nil { + return false, fmt.Errorf("ent: check existence: %w", err) + } + return n > 0, nil +} + +func (tlq *TweetLikeQuery) querySpec() *sqlgraph.QuerySpec { + _spec := &sqlgraph.QuerySpec{ + Node: &sqlgraph.NodeSpec{ + Table: tweetlike.Table, + Columns: tweetlike.Columns, + }, + From: tlq.sql, + Unique: true, + } + if unique := tlq.unique; unique != nil { + _spec.Unique = *unique + } + if fields := tlq.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + for i := range fields { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if ps := tlq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := tlq.limit; limit != nil { + _spec.Limit = *limit + } + if offset := tlq.offset; offset != nil { + _spec.Offset = *offset + } + if ps := tlq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (tlq *TweetLikeQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(tlq.driver.Dialect()) + t1 := builder.Table(tweetlike.Table) + columns := tlq.fields + if len(columns) == 0 { + columns = tweetlike.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if tlq.sql != nil { + selector = tlq.sql + selector.Select(selector.Columns(columns...)...) + } + if tlq.unique != nil && *tlq.unique { + selector.Distinct() + } + for _, p := range tlq.predicates { + p(selector) + } + for _, p := range tlq.order { + p(selector) + } + if offset := tlq.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 := tlq.limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// TweetLikeGroupBy is the group-by builder for TweetLike entities. +type TweetLikeGroupBy 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 (tlgb *TweetLikeGroupBy) Aggregate(fns ...AggregateFunc) *TweetLikeGroupBy { + tlgb.fns = append(tlgb.fns, fns...) + return tlgb +} + +// Scan applies the group-by query and scans the result into the given value. +func (tlgb *TweetLikeGroupBy) Scan(ctx context.Context, v interface{}) error { + query, err := tlgb.path(ctx) + if err != nil { + return err + } + tlgb.sql = query + return tlgb.sqlScan(ctx, v) +} + +func (tlgb *TweetLikeGroupBy) sqlScan(ctx context.Context, v interface{}) error { + for _, f := range tlgb.fields { + if !tweetlike.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)} + } + } + selector := tlgb.sqlQuery() + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := tlgb.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +func (tlgb *TweetLikeGroupBy) sqlQuery() *sql.Selector { + selector := tlgb.sql.Select() + aggregation := make([]string, 0, len(tlgb.fns)) + for _, fn := range tlgb.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(tlgb.fields)+len(tlgb.fns)) + for _, f := range tlgb.fields { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + return selector.GroupBy(selector.Columns(tlgb.fields...)...) +} + +// TweetLikeSelect is the builder for selecting fields of TweetLike entities. +type TweetLikeSelect struct { + *TweetLikeQuery + selector + // intermediate query (i.e. traversal path). + sql *sql.Selector +} + +// Scan applies the selector query and scans the result into the given value. +func (tls *TweetLikeSelect) Scan(ctx context.Context, v interface{}) error { + if err := tls.prepareQuery(ctx); err != nil { + return err + } + tls.sql = tls.TweetLikeQuery.sqlQuery(ctx) + return tls.sqlScan(ctx, v) +} + +func (tls *TweetLikeSelect) sqlScan(ctx context.Context, v interface{}) error { + rows := &sql.Rows{} + query, args := tls.sql.Query() + if err := tls.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/tweetlike_update.go b/entc/integration/edgeschema/ent/tweetlike_update.go new file mode 100644 index 0000000000..f278dd5111 --- /dev/null +++ b/entc/integration/edgeschema/ent/tweetlike_update.go @@ -0,0 +1,516 @@ +// Code generated by entc, 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/tweet" + "entgo.io/ent/entc/integration/edgeschema/ent/tweetlike" + "entgo.io/ent/entc/integration/edgeschema/ent/user" + "entgo.io/ent/schema/field" +) + +// TweetLikeUpdate is the builder for updating TweetLike entities. +type TweetLikeUpdate struct { + config + hooks []Hook + mutation *TweetLikeMutation +} + +// Where appends a list predicates to the TweetLikeUpdate builder. +func (tlu *TweetLikeUpdate) Where(ps ...predicate.TweetLike) *TweetLikeUpdate { + tlu.mutation.Where(ps...) + return tlu +} + +// SetLikedAt sets the "liked_at" field. +func (tlu *TweetLikeUpdate) SetLikedAt(t time.Time) *TweetLikeUpdate { + tlu.mutation.SetLikedAt(t) + return tlu +} + +// SetNillableLikedAt sets the "liked_at" field if the given value is not nil. +func (tlu *TweetLikeUpdate) SetNillableLikedAt(t *time.Time) *TweetLikeUpdate { + if t != nil { + tlu.SetLikedAt(*t) + } + return tlu +} + +// SetUserID sets the "user_id" field. +func (tlu *TweetLikeUpdate) SetUserID(i int) *TweetLikeUpdate { + tlu.mutation.SetUserID(i) + return tlu +} + +// SetTweetID sets the "tweet_id" field. +func (tlu *TweetLikeUpdate) SetTweetID(i int) *TweetLikeUpdate { + tlu.mutation.SetTweetID(i) + return tlu +} + +// SetUser sets the "user" edge to the User entity. +func (tlu *TweetLikeUpdate) SetUser(u *User) *TweetLikeUpdate { + return tlu.SetUserID(u.ID) +} + +// SetTweet sets the "tweet" edge to the Tweet entity. +func (tlu *TweetLikeUpdate) SetTweet(t *Tweet) *TweetLikeUpdate { + return tlu.SetTweetID(t.ID) +} + +// Mutation returns the TweetLikeMutation object of the builder. +func (tlu *TweetLikeUpdate) Mutation() *TweetLikeMutation { + return tlu.mutation +} + +// ClearUser clears the "user" edge to the User entity. +func (tlu *TweetLikeUpdate) ClearUser() *TweetLikeUpdate { + tlu.mutation.ClearUser() + return tlu +} + +// ClearTweet clears the "tweet" edge to the Tweet entity. +func (tlu *TweetLikeUpdate) ClearTweet() *TweetLikeUpdate { + tlu.mutation.ClearTweet() + return tlu +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (tlu *TweetLikeUpdate) Save(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(tlu.hooks) == 0 { + if err = tlu.check(); err != nil { + return 0, err + } + affected, err = tlu.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*TweetLikeMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err = tlu.check(); err != nil { + return 0, err + } + tlu.mutation = mutation + affected, err = tlu.sqlSave(ctx) + mutation.done = true + return affected, err + }) + for i := len(tlu.hooks) - 1; i >= 0; i-- { + if tlu.hooks[i] == nil { + return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = tlu.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, tlu.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// SaveX is like Save, but panics if an error occurs. +func (tlu *TweetLikeUpdate) SaveX(ctx context.Context) int { + affected, err := tlu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (tlu *TweetLikeUpdate) Exec(ctx context.Context) error { + _, err := tlu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (tlu *TweetLikeUpdate) ExecX(ctx context.Context) { + if err := tlu.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (tlu *TweetLikeUpdate) check() error { + if _, ok := tlu.mutation.UserID(); tlu.mutation.UserCleared() && !ok { + return errors.New(`ent: clearing a required unique edge "TweetLike.user"`) + } + if _, ok := tlu.mutation.TweetID(); tlu.mutation.TweetCleared() && !ok { + return errors.New(`ent: clearing a required unique edge "TweetLike.tweet"`) + } + return nil +} + +func (tlu *TweetLikeUpdate) sqlSave(ctx context.Context) (n int, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: tweetlike.Table, + Columns: tweetlike.Columns, + }, + } + if ps := tlu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := tlu.mutation.LikedAt(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: tweetlike.FieldLikedAt, + }) + } + if tlu.mutation.UserCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: tweetlike.UserTable, + Columns: []string{tweetlike.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := tlu.mutation.UserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: tweetlike.UserTable, + Columns: []string{tweetlike.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if tlu.mutation.TweetCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: tweetlike.TweetTable, + Columns: []string{tweetlike.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 := tlu.mutation.TweetIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: tweetlike.TweetTable, + Columns: []string{tweetlike.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, tlu.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{tweetlike.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return 0, err + } + return n, nil +} + +// TweetLikeUpdateOne is the builder for updating a single TweetLike entity. +type TweetLikeUpdateOne struct { + config + fields []string + hooks []Hook + mutation *TweetLikeMutation +} + +// SetLikedAt sets the "liked_at" field. +func (tluo *TweetLikeUpdateOne) SetLikedAt(t time.Time) *TweetLikeUpdateOne { + tluo.mutation.SetLikedAt(t) + return tluo +} + +// SetNillableLikedAt sets the "liked_at" field if the given value is not nil. +func (tluo *TweetLikeUpdateOne) SetNillableLikedAt(t *time.Time) *TweetLikeUpdateOne { + if t != nil { + tluo.SetLikedAt(*t) + } + return tluo +} + +// SetUserID sets the "user_id" field. +func (tluo *TweetLikeUpdateOne) SetUserID(i int) *TweetLikeUpdateOne { + tluo.mutation.SetUserID(i) + return tluo +} + +// SetTweetID sets the "tweet_id" field. +func (tluo *TweetLikeUpdateOne) SetTweetID(i int) *TweetLikeUpdateOne { + tluo.mutation.SetTweetID(i) + return tluo +} + +// SetUser sets the "user" edge to the User entity. +func (tluo *TweetLikeUpdateOne) SetUser(u *User) *TweetLikeUpdateOne { + return tluo.SetUserID(u.ID) +} + +// SetTweet sets the "tweet" edge to the Tweet entity. +func (tluo *TweetLikeUpdateOne) SetTweet(t *Tweet) *TweetLikeUpdateOne { + return tluo.SetTweetID(t.ID) +} + +// Mutation returns the TweetLikeMutation object of the builder. +func (tluo *TweetLikeUpdateOne) Mutation() *TweetLikeMutation { + return tluo.mutation +} + +// ClearUser clears the "user" edge to the User entity. +func (tluo *TweetLikeUpdateOne) ClearUser() *TweetLikeUpdateOne { + tluo.mutation.ClearUser() + return tluo +} + +// ClearTweet clears the "tweet" edge to the Tweet entity. +func (tluo *TweetLikeUpdateOne) ClearTweet() *TweetLikeUpdateOne { + tluo.mutation.ClearTweet() + return tluo +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (tluo *TweetLikeUpdateOne) Select(field string, fields ...string) *TweetLikeUpdateOne { + tluo.fields = append([]string{field}, fields...) + return tluo +} + +// Save executes the query and returns the updated TweetLike entity. +func (tluo *TweetLikeUpdateOne) Save(ctx context.Context) (*TweetLike, error) { + var ( + err error + node *TweetLike + ) + if len(tluo.hooks) == 0 { + if err = tluo.check(); err != nil { + return nil, err + } + node, err = tluo.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*TweetLikeMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err = tluo.check(); err != nil { + return nil, err + } + tluo.mutation = mutation + node, err = tluo.sqlSave(ctx) + mutation.done = true + return node, err + }) + for i := len(tluo.hooks) - 1; i >= 0; i-- { + if tluo.hooks[i] == nil { + return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = tluo.hooks[i](mut) + } + v, err := mut.Mutate(ctx, tluo.mutation) + if err != nil { + return nil, err + } + nv, ok := v.(*TweetLike) + if !ok { + return nil, fmt.Errorf("unexpected node type %T returned from TweetLikeMutation", v) + } + node = nv + } + return node, err +} + +// SaveX is like Save, but panics if an error occurs. +func (tluo *TweetLikeUpdateOne) SaveX(ctx context.Context) *TweetLike { + node, err := tluo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (tluo *TweetLikeUpdateOne) Exec(ctx context.Context) error { + _, err := tluo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (tluo *TweetLikeUpdateOne) ExecX(ctx context.Context) { + if err := tluo.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (tluo *TweetLikeUpdateOne) check() error { + if _, ok := tluo.mutation.UserID(); tluo.mutation.UserCleared() && !ok { + return errors.New(`ent: clearing a required unique edge "TweetLike.user"`) + } + if _, ok := tluo.mutation.TweetID(); tluo.mutation.TweetCleared() && !ok { + return errors.New(`ent: clearing a required unique edge "TweetLike.tweet"`) + } + return nil +} + +func (tluo *TweetLikeUpdateOne) sqlSave(ctx context.Context) (_node *TweetLike, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: tweetlike.Table, + Columns: tweetlike.Columns, + }, + } + if fields := tluo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, len(fields)) + for i, f := range fields { + if !tweetlike.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + _spec.Node.Columns[i] = f + } + } + if ps := tluo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := tluo.mutation.LikedAt(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: tweetlike.FieldLikedAt, + }) + } + if tluo.mutation.UserCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: tweetlike.UserTable, + Columns: []string{tweetlike.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := tluo.mutation.UserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: tweetlike.UserTable, + Columns: []string{tweetlike.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if tluo.mutation.TweetCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: tweetlike.TweetTable, + Columns: []string{tweetlike.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 := tluo.mutation.TweetIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: tweetlike.TweetTable, + Columns: []string{tweetlike.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 = &TweetLike{config: tluo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, tluo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{tweetlike.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return nil, err + } + return _node, nil +} diff --git a/entc/integration/edgeschema/ent/tx.go b/entc/integration/edgeschema/ent/tx.go new file mode 100644 index 0000000000..cdee951bab --- /dev/null +++ b/entc/integration/edgeschema/ent/tx.go @@ -0,0 +1,228 @@ +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "sync" + + "entgo.io/ent/dialect" +) + +// Tx is a transactional client that is created by calling Client.Tx(). +type Tx struct { + config + // Friendship is the client for interacting with the Friendship builders. + Friendship *FriendshipClient + // Group is the client for interacting with the Group builders. + Group *GroupClient + // Relationship is the client for interacting with the Relationship builders. + Relationship *RelationshipClient + // Tweet is the client for interacting with the Tweet builders. + Tweet *TweetClient + // TweetLike is the client for interacting with the TweetLike builders. + TweetLike *TweetLikeClient + // User is the client for interacting with the User builders. + User *UserClient + // UserGroup is the client for interacting with the UserGroup builders. + UserGroup *UserGroupClient + + // lazily loaded. + client *Client + clientOnce sync.Once + + // completion callbacks. + mu sync.Mutex + onCommit []CommitHook + onRollback []RollbackHook + + // ctx lives for the life of the transaction. It is + // the same context used by the underlying connection. + ctx context.Context +} + +type ( + // Committer is the interface that wraps the Commit method. + Committer interface { + Commit(context.Context, *Tx) error + } + + // The CommitFunc type is an adapter to allow the use of ordinary + // function as a Committer. If f is a function with the appropriate + // signature, CommitFunc(f) is a Committer that calls f. + CommitFunc func(context.Context, *Tx) error + + // CommitHook defines the "commit middleware". A function that gets a Committer + // and returns a Committer. For example: + // + // hook := func(next ent.Committer) ent.Committer { + // return ent.CommitFunc(func(ctx context.Context, tx *ent.Tx) error { + // // Do some stuff before. + // if err := next.Commit(ctx, tx); err != nil { + // return err + // } + // // Do some stuff after. + // return nil + // }) + // } + // + CommitHook func(Committer) Committer +) + +// Commit calls f(ctx, m). +func (f CommitFunc) Commit(ctx context.Context, tx *Tx) error { + return f(ctx, tx) +} + +// Commit commits the transaction. +func (tx *Tx) Commit() error { + txDriver := tx.config.driver.(*txDriver) + var fn Committer = CommitFunc(func(context.Context, *Tx) error { + return txDriver.tx.Commit() + }) + tx.mu.Lock() + hooks := append([]CommitHook(nil), tx.onCommit...) + tx.mu.Unlock() + for i := len(hooks) - 1; i >= 0; i-- { + fn = hooks[i](fn) + } + return fn.Commit(tx.ctx, tx) +} + +// OnCommit adds a hook to call on commit. +func (tx *Tx) OnCommit(f CommitHook) { + tx.mu.Lock() + defer tx.mu.Unlock() + tx.onCommit = append(tx.onCommit, f) +} + +type ( + // Rollbacker is the interface that wraps the Rollback method. + Rollbacker interface { + Rollback(context.Context, *Tx) error + } + + // The RollbackFunc type is an adapter to allow the use of ordinary + // function as a Rollbacker. If f is a function with the appropriate + // signature, RollbackFunc(f) is a Rollbacker that calls f. + RollbackFunc func(context.Context, *Tx) error + + // RollbackHook defines the "rollback middleware". A function that gets a Rollbacker + // and returns a Rollbacker. For example: + // + // hook := func(next ent.Rollbacker) ent.Rollbacker { + // return ent.RollbackFunc(func(ctx context.Context, tx *ent.Tx) error { + // // Do some stuff before. + // if err := next.Rollback(ctx, tx); err != nil { + // return err + // } + // // Do some stuff after. + // return nil + // }) + // } + // + RollbackHook func(Rollbacker) Rollbacker +) + +// Rollback calls f(ctx, m). +func (f RollbackFunc) Rollback(ctx context.Context, tx *Tx) error { + return f(ctx, tx) +} + +// Rollback rollbacks the transaction. +func (tx *Tx) Rollback() error { + txDriver := tx.config.driver.(*txDriver) + var fn Rollbacker = RollbackFunc(func(context.Context, *Tx) error { + return txDriver.tx.Rollback() + }) + tx.mu.Lock() + hooks := append([]RollbackHook(nil), tx.onRollback...) + tx.mu.Unlock() + for i := len(hooks) - 1; i >= 0; i-- { + fn = hooks[i](fn) + } + return fn.Rollback(tx.ctx, tx) +} + +// OnRollback adds a hook to call on rollback. +func (tx *Tx) OnRollback(f RollbackHook) { + tx.mu.Lock() + defer tx.mu.Unlock() + tx.onRollback = append(tx.onRollback, f) +} + +// Client returns a Client that binds to current transaction. +func (tx *Tx) Client() *Client { + tx.clientOnce.Do(func() { + tx.client = &Client{config: tx.config} + tx.client.init() + }) + return tx.client +} + +func (tx *Tx) init() { + tx.Friendship = NewFriendshipClient(tx.config) + tx.Group = NewGroupClient(tx.config) + tx.Relationship = NewRelationshipClient(tx.config) + tx.Tweet = NewTweetClient(tx.config) + tx.TweetLike = NewTweetLikeClient(tx.config) + tx.User = NewUserClient(tx.config) + tx.UserGroup = NewUserGroupClient(tx.config) +} + +// txDriver wraps the given dialect.Tx with a nop dialect.Driver implementation. +// The idea is to support transactions without adding any extra code to the builders. +// When a builder calls to driver.Tx(), it gets the same dialect.Tx instance. +// Commit and Rollback are nop for the internal builders and the user must call one +// of them in order to commit or rollback the transaction. +// +// If a closed transaction is embedded in one of the generated entities, and the entity +// applies a query, for example: Friendship.QueryXXX(), the query will be executed +// through the driver which created this transaction. +// +// Note that txDriver is not goroutine safe. +type txDriver struct { + // the driver we started the transaction from. + drv dialect.Driver + // tx is the underlying transaction. + tx dialect.Tx +} + +// newTx creates a new transactional driver. +func newTx(ctx context.Context, drv dialect.Driver) (*txDriver, error) { + tx, err := drv.Tx(ctx) + if err != nil { + return nil, err + } + return &txDriver{tx: tx, drv: drv}, nil +} + +// Tx returns the transaction wrapper (txDriver) to avoid Commit or Rollback calls +// from the internal builders. Should be called only by the internal builders. +func (tx *txDriver) Tx(context.Context) (dialect.Tx, error) { return tx, nil } + +// Dialect returns the dialect of the driver we started the transaction from. +func (tx *txDriver) Dialect() string { return tx.drv.Dialect() } + +// Close is a nop close. +func (*txDriver) Close() error { return nil } + +// Commit is a nop commit for the internal builders. +// User must call `Tx.Commit` in order to commit the transaction. +func (*txDriver) Commit() error { return nil } + +// Rollback is a nop rollback for the internal builders. +// User must call `Tx.Rollback` in order to rollback the transaction. +func (*txDriver) Rollback() error { return nil } + +// Exec calls tx.Exec. +func (tx *txDriver) Exec(ctx context.Context, query string, args, v interface{}) error { + return tx.tx.Exec(ctx, query, args, v) +} + +// Query calls tx.Query. +func (tx *txDriver) Query(ctx context.Context, query string, args, v interface{}) error { + return tx.tx.Query(ctx, query, args, v) +} + +var _ dialect.Driver = (*txDriver)(nil) diff --git a/entc/integration/edgeschema/ent/user.go b/entc/integration/edgeschema/ent/user.go new file mode 100644 index 0000000000..e39a7e6876 --- /dev/null +++ b/entc/integration/edgeschema/ent/user.go @@ -0,0 +1,237 @@ +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "fmt" + "strings" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/entc/integration/edgeschema/ent/user" +) + +// User is the model entity for the User schema. +type User struct { + config `json:"-"` + // ID of the ent. + ID int `json:"id,omitempty"` + // Name holds the value of the "name" field. + Name string `json:"name,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the UserQuery when eager-loading is set. + Edges UserEdges `json:"edges"` +} + +// UserEdges holds the relations/edges for other nodes in the graph. +type UserEdges struct { + // LikedTweets holds the value of the liked_tweets edge. + LikedTweets []*Tweet `json:"liked_tweets,omitempty"` + // Groups holds the value of the groups edge. + Groups []*Group `json:"groups,omitempty"` + // Friends holds the value of the friends edge. + Friends []*User `json:"friends,omitempty"` + // Relatives holds the value of the relatives edge. + Relatives []*User `json:"relatives,omitempty"` + // Likes holds the value of the likes edge. + Likes []*TweetLike `json:"likes,omitempty"` + // JoinedGroups holds the value of the joined_groups edge. + JoinedGroups []*UserGroup `json:"joined_groups,omitempty"` + // Friendships holds the value of the friendships edge. + Friendships []*Friendship `json:"friendships,omitempty"` + // Relationship holds the value of the relationship edge. + Relationship []*Relationship `json:"relationship,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [8]bool +} + +// LikedTweetsOrErr returns the LikedTweets value or an error if the edge +// was not loaded in eager-loading. +func (e UserEdges) LikedTweetsOrErr() ([]*Tweet, error) { + if e.loadedTypes[0] { + return e.LikedTweets, nil + } + return nil, &NotLoadedError{edge: "liked_tweets"} +} + +// GroupsOrErr returns the Groups value or an error if the edge +// was not loaded in eager-loading. +func (e UserEdges) GroupsOrErr() ([]*Group, error) { + if e.loadedTypes[1] { + return e.Groups, nil + } + return nil, &NotLoadedError{edge: "groups"} +} + +// FriendsOrErr returns the Friends value or an error if the edge +// was not loaded in eager-loading. +func (e UserEdges) FriendsOrErr() ([]*User, error) { + if e.loadedTypes[2] { + return e.Friends, nil + } + return nil, &NotLoadedError{edge: "friends"} +} + +// RelativesOrErr returns the Relatives value or an error if the edge +// was not loaded in eager-loading. +func (e UserEdges) RelativesOrErr() ([]*User, error) { + if e.loadedTypes[3] { + return e.Relatives, nil + } + return nil, &NotLoadedError{edge: "relatives"} +} + +// LikesOrErr returns the Likes value or an error if the edge +// was not loaded in eager-loading. +func (e UserEdges) LikesOrErr() ([]*TweetLike, error) { + if e.loadedTypes[4] { + return e.Likes, nil + } + return nil, &NotLoadedError{edge: "likes"} +} + +// JoinedGroupsOrErr returns the JoinedGroups value or an error if the edge +// was not loaded in eager-loading. +func (e UserEdges) JoinedGroupsOrErr() ([]*UserGroup, error) { + if e.loadedTypes[5] { + return e.JoinedGroups, nil + } + return nil, &NotLoadedError{edge: "joined_groups"} +} + +// FriendshipsOrErr returns the Friendships value or an error if the edge +// was not loaded in eager-loading. +func (e UserEdges) FriendshipsOrErr() ([]*Friendship, error) { + if e.loadedTypes[6] { + return e.Friendships, nil + } + return nil, &NotLoadedError{edge: "friendships"} +} + +// RelationshipOrErr returns the Relationship value or an error if the edge +// was not loaded in eager-loading. +func (e UserEdges) RelationshipOrErr() ([]*Relationship, error) { + if e.loadedTypes[7] { + return e.Relationship, nil + } + return nil, &NotLoadedError{edge: "relationship"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*User) scanValues(columns []string) ([]interface{}, error) { + values := make([]interface{}, len(columns)) + for i := range columns { + switch columns[i] { + case user.FieldID: + values[i] = new(sql.NullInt64) + case user.FieldName: + values[i] = new(sql.NullString) + default: + return nil, fmt.Errorf("unexpected column %q for type User", columns[i]) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the User fields. +func (u *User) assignValues(columns []string, values []interface{}) error { + if m, n := len(values), len(columns); m < n { + return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) + } + for i := range columns { + switch columns[i] { + case user.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + u.ID = int(value.Int64) + case user.FieldName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field name", values[i]) + } else if value.Valid { + u.Name = value.String + } + } + } + return nil +} + +// QueryLikedTweets queries the "liked_tweets" edge of the User entity. +func (u *User) QueryLikedTweets() *TweetQuery { + return (&UserClient{config: u.config}).QueryLikedTweets(u) +} + +// QueryGroups queries the "groups" edge of the User entity. +func (u *User) QueryGroups() *GroupQuery { + return (&UserClient{config: u.config}).QueryGroups(u) +} + +// QueryFriends queries the "friends" edge of the User entity. +func (u *User) QueryFriends() *UserQuery { + return (&UserClient{config: u.config}).QueryFriends(u) +} + +// QueryRelatives queries the "relatives" edge of the User entity. +func (u *User) QueryRelatives() *UserQuery { + return (&UserClient{config: u.config}).QueryRelatives(u) +} + +// QueryLikes queries the "likes" edge of the User entity. +func (u *User) QueryLikes() *TweetLikeQuery { + return (&UserClient{config: u.config}).QueryLikes(u) +} + +// QueryJoinedGroups queries the "joined_groups" edge of the User entity. +func (u *User) QueryJoinedGroups() *UserGroupQuery { + return (&UserClient{config: u.config}).QueryJoinedGroups(u) +} + +// QueryFriendships queries the "friendships" edge of the User entity. +func (u *User) QueryFriendships() *FriendshipQuery { + return (&UserClient{config: u.config}).QueryFriendships(u) +} + +// QueryRelationship queries the "relationship" edge of the User entity. +func (u *User) QueryRelationship() *RelationshipQuery { + return (&UserClient{config: u.config}).QueryRelationship(u) +} + +// Update returns a builder for updating this User. +// Note that you need to call User.Unwrap() before calling this method if this User +// was returned from a transaction, and the transaction was committed or rolled back. +func (u *User) Update() *UserUpdateOne { + return (&UserClient{config: u.config}).UpdateOne(u) +} + +// Unwrap unwraps the User entity that was returned from a transaction after it was closed, +// so that all future queries will be executed through the driver which created the transaction. +func (u *User) Unwrap() *User { + tx, ok := u.config.driver.(*txDriver) + if !ok { + panic("ent: User is not a transactional entity") + } + u.config.driver = tx.drv + return u +} + +// String implements the fmt.Stringer. +func (u *User) String() string { + var builder strings.Builder + builder.WriteString("User(") + builder.WriteString(fmt.Sprintf("id=%v, ", u.ID)) + builder.WriteString("name=") + builder.WriteString(u.Name) + builder.WriteByte(')') + return builder.String() +} + +// Users is a parsable slice of User. +type Users []*User + +func (u Users) config(cfg config) { + for _i := range u { + u[_i].config = cfg + } +} diff --git a/entc/integration/edgeschema/ent/user/user.go b/entc/integration/edgeschema/ent/user/user.go new file mode 100644 index 0000000000..e73847ff15 --- /dev/null +++ b/entc/integration/edgeschema/ent/user/user.go @@ -0,0 +1,108 @@ +// Code generated by entc, DO NOT EDIT. + +package user + +const ( + // Label holds the string label denoting the user type in the database. + Label = "user" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldName holds the string denoting the name field in the database. + FieldName = "name" + // EdgeLikedTweets holds the string denoting the liked_tweets edge name in mutations. + EdgeLikedTweets = "liked_tweets" + // EdgeGroups holds the string denoting the groups edge name in mutations. + EdgeGroups = "groups" + // EdgeFriends holds the string denoting the friends edge name in mutations. + EdgeFriends = "friends" + // EdgeRelatives holds the string denoting the relatives edge name in mutations. + EdgeRelatives = "relatives" + // EdgeLikes holds the string denoting the likes edge name in mutations. + EdgeLikes = "likes" + // EdgeJoinedGroups holds the string denoting the joined_groups edge name in mutations. + EdgeJoinedGroups = "joined_groups" + // EdgeFriendships holds the string denoting the friendships edge name in mutations. + EdgeFriendships = "friendships" + // EdgeRelationship holds the string denoting the relationship edge name in mutations. + EdgeRelationship = "relationship" + // Table holds the table name of the user in the database. + Table = "users" + // LikedTweetsTable is the table that holds the liked_tweets relation/edge. The primary key declared below. + LikedTweetsTable = "tweet_likes" + // LikedTweetsInverseTable is the table name for the Tweet entity. + // It exists in this package in order to avoid circular dependency with the "tweet" package. + LikedTweetsInverseTable = "tweets" + // GroupsTable is the table that holds the groups relation/edge. The primary key declared below. + GroupsTable = "user_groups" + // GroupsInverseTable is the table name for the Group entity. + // It exists in this package in order to avoid circular dependency with the "group" package. + GroupsInverseTable = "groups" + // FriendsTable is the table that holds the friends relation/edge. The primary key declared below. + FriendsTable = "friendships" + // RelativesTable is the table that holds the relatives relation/edge. The primary key declared below. + RelativesTable = "relationships" + // LikesTable is the table that holds the likes relation/edge. + LikesTable = "tweet_likes" + // LikesInverseTable is the table name for the TweetLike entity. + // It exists in this package in order to avoid circular dependency with the "tweetlike" package. + LikesInverseTable = "tweet_likes" + // LikesColumn is the table column denoting the likes relation/edge. + LikesColumn = "user_id" + // JoinedGroupsTable is the table that holds the joined_groups relation/edge. + JoinedGroupsTable = "user_groups" + // JoinedGroupsInverseTable is the table name for the UserGroup entity. + // It exists in this package in order to avoid circular dependency with the "usergroup" package. + JoinedGroupsInverseTable = "user_groups" + // JoinedGroupsColumn is the table column denoting the joined_groups relation/edge. + JoinedGroupsColumn = "user_id" + // FriendshipsTable is the table that holds the friendships relation/edge. + FriendshipsTable = "friendships" + // FriendshipsInverseTable is the table name for the Friendship entity. + // It exists in this package in order to avoid circular dependency with the "friendship" package. + FriendshipsInverseTable = "friendships" + // FriendshipsColumn is the table column denoting the friendships relation/edge. + FriendshipsColumn = "user_id" + // RelationshipTable is the table that holds the relationship relation/edge. + RelationshipTable = "relationships" + // RelationshipInverseTable is the table name for the Relationship entity. + // It exists in this package in order to avoid circular dependency with the "relationship" package. + RelationshipInverseTable = "relationships" + // RelationshipColumn is the table column denoting the relationship relation/edge. + RelationshipColumn = "user_id" +) + +// Columns holds all SQL columns for user fields. +var Columns = []string{ + FieldID, + FieldName, +} + +var ( + // LikedTweetsPrimaryKey and LikedTweetsColumn2 are the table columns denoting the + // primary key for the liked_tweets relation (M2M). + LikedTweetsPrimaryKey = []string{"user_id", "tweet_id"} + // GroupsPrimaryKey and GroupsColumn2 are the table columns denoting the + // primary key for the groups relation (M2M). + GroupsPrimaryKey = []string{"user_id", "group_id"} + // FriendsPrimaryKey and FriendsColumn2 are the table columns denoting the + // primary key for the friends relation (M2M). + FriendsPrimaryKey = []string{"user_id", "friend_id"} + // RelativesPrimaryKey and RelativesColumn2 are the table columns denoting the + // primary key for the relatives relation (M2M). + RelativesPrimaryKey = []string{"user_id", "relative_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 +} + +var ( + // DefaultName holds the default value on creation for the "name" field. + DefaultName string +) diff --git a/entc/integration/edgeschema/ent/user/where.go b/entc/integration/edgeschema/ent/user/where.go new file mode 100644 index 0000000000..47fa257542 --- /dev/null +++ b/entc/integration/edgeschema/ent/user/where.go @@ -0,0 +1,466 @@ +// Code generated by entc, DO NOT EDIT. + +package user + +import ( + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/edgeschema/ent/predicate" +) + +// ID filters vertices based on their ID field. +func ID(id int) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldID), id)) + }) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldID), id)) + }) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldID), id)) + }) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int) predicate.User { + return predicate.User(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(ids) == 0 { + s.Where(sql.False()) + return + } + v := make([]interface{}, len(ids)) + for i := range v { + v[i] = ids[i] + } + s.Where(sql.In(s.C(FieldID), v...)) + }) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int) predicate.User { + return predicate.User(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(ids) == 0 { + s.Where(sql.False()) + return + } + v := make([]interface{}, len(ids)) + for i := range v { + v[i] = ids[i] + } + s.Where(sql.NotIn(s.C(FieldID), v...)) + }) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldID), id)) + }) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldID), id)) + }) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldID), id)) + }) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldID), id)) + }) +} + +// Name applies equality check predicate on the "name" field. It's identical to NameEQ. +func Name(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldName), v)) + }) +} + +// NameEQ applies the EQ predicate on the "name" field. +func NameEQ(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldName), v)) + }) +} + +// NameNEQ applies the NEQ predicate on the "name" field. +func NameNEQ(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldName), v)) + }) +} + +// NameIn applies the In predicate on the "name" field. +func NameIn(vs ...string) predicate.User { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.User(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldName), v...)) + }) +} + +// NameNotIn applies the NotIn predicate on the "name" field. +func NameNotIn(vs ...string) predicate.User { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.User(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldName), v...)) + }) +} + +// NameGT applies the GT predicate on the "name" field. +func NameGT(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldName), v)) + }) +} + +// NameGTE applies the GTE predicate on the "name" field. +func NameGTE(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldName), v)) + }) +} + +// NameLT applies the LT predicate on the "name" field. +func NameLT(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldName), v)) + }) +} + +// NameLTE applies the LTE predicate on the "name" field. +func NameLTE(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldName), v)) + }) +} + +// NameContains applies the Contains predicate on the "name" field. +func NameContains(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldName), v)) + }) +} + +// NameHasPrefix applies the HasPrefix predicate on the "name" field. +func NameHasPrefix(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldName), v)) + }) +} + +// NameHasSuffix applies the HasSuffix predicate on the "name" field. +func NameHasSuffix(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldName), v)) + }) +} + +// NameEqualFold applies the EqualFold predicate on the "name" field. +func NameEqualFold(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldName), v)) + }) +} + +// NameContainsFold applies the ContainsFold predicate on the "name" field. +func NameContainsFold(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldName), v)) + }) +} + +// HasLikedTweets applies the HasEdge predicate on the "liked_tweets" edge. +func HasLikedTweets() predicate.User { + return predicate.User(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(LikedTweetsTable, FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, LikedTweetsTable, LikedTweetsPrimaryKey...), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasLikedTweetsWith applies the HasEdge predicate on the "liked_tweets" edge with a given conditions (other predicates). +func HasLikedTweetsWith(preds ...predicate.Tweet) predicate.User { + return predicate.User(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(LikedTweetsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, LikedTweetsTable, LikedTweetsPrimaryKey...), + ) + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasGroups applies the HasEdge predicate on the "groups" edge. +func HasGroups() predicate.User { + return predicate.User(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(GroupsTable, FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, GroupsTable, GroupsPrimaryKey...), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasGroupsWith applies the HasEdge predicate on the "groups" edge with a given conditions (other predicates). +func HasGroupsWith(preds ...predicate.Group) predicate.User { + return predicate.User(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(GroupsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, GroupsTable, GroupsPrimaryKey...), + ) + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasFriends applies the HasEdge predicate on the "friends" edge. +func HasFriends() predicate.User { + return predicate.User(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(FriendsTable, FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, FriendsTable, FriendsPrimaryKey...), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasFriendsWith applies the HasEdge predicate on the "friends" edge with a given conditions (other predicates). +func HasFriendsWith(preds ...predicate.User) predicate.User { + return predicate.User(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, FriendsTable, FriendsPrimaryKey...), + ) + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasRelatives applies the HasEdge predicate on the "relatives" edge. +func HasRelatives() predicate.User { + return predicate.User(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(RelativesTable, FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, RelativesTable, RelativesPrimaryKey...), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasRelativesWith applies the HasEdge predicate on the "relatives" edge with a given conditions (other predicates). +func HasRelativesWith(preds ...predicate.User) predicate.User { + return predicate.User(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, RelativesTable, RelativesPrimaryKey...), + ) + 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.User { + return predicate.User(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(LikesTable, LikesColumn), + sqlgraph.Edge(sqlgraph.O2M, true, LikesTable, LikesColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasLikesWith applies the HasEdge predicate on the "likes" edge with a given conditions (other predicates). +func HasLikesWith(preds ...predicate.TweetLike) predicate.User { + return predicate.User(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(LikesInverseTable, LikesColumn), + sqlgraph.Edge(sqlgraph.O2M, true, LikesTable, LikesColumn), + ) + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasJoinedGroups applies the HasEdge predicate on the "joined_groups" edge. +func HasJoinedGroups() predicate.User { + return predicate.User(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(JoinedGroupsTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, JoinedGroupsTable, JoinedGroupsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasJoinedGroupsWith applies the HasEdge predicate on the "joined_groups" edge with a given conditions (other predicates). +func HasJoinedGroupsWith(preds ...predicate.UserGroup) predicate.User { + return predicate.User(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(JoinedGroupsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, JoinedGroupsTable, JoinedGroupsColumn), + ) + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasFriendships applies the HasEdge predicate on the "friendships" edge. +func HasFriendships() predicate.User { + return predicate.User(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(FriendshipsTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, FriendshipsTable, FriendshipsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasFriendshipsWith applies the HasEdge predicate on the "friendships" edge with a given conditions (other predicates). +func HasFriendshipsWith(preds ...predicate.Friendship) predicate.User { + return predicate.User(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(FriendshipsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, FriendshipsTable, FriendshipsColumn), + ) + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasRelationship applies the HasEdge predicate on the "relationship" edge. +func HasRelationship() predicate.User { + return predicate.User(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(RelationshipTable, RelationshipColumn), + sqlgraph.Edge(sqlgraph.O2M, true, RelationshipTable, RelationshipColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasRelationshipWith applies the HasEdge predicate on the "relationship" edge with a given conditions (other predicates). +func HasRelationshipWith(preds ...predicate.Relationship) predicate.User { + return predicate.User(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(RelationshipInverseTable, RelationshipColumn), + sqlgraph.Edge(sqlgraph.O2M, true, RelationshipTable, RelationshipColumn), + ) + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.User) predicate.User { + return predicate.User(func(s *sql.Selector) { + s1 := s.Clone().SetP(nil) + for _, p := range predicates { + p(s1) + } + s.Where(s1.P()) + }) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.User) predicate.User { + return predicate.User(func(s *sql.Selector) { + s1 := s.Clone().SetP(nil) + for i, p := range predicates { + if i > 0 { + s1.Or() + } + p(s1) + } + s.Where(s1.P()) + }) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.User) predicate.User { + return predicate.User(func(s *sql.Selector) { + p(s.Not()) + }) +} diff --git a/entc/integration/edgeschema/ent/user_create.go b/entc/integration/edgeschema/ent/user_create.go new file mode 100644 index 0000000000..633e3fd9de --- /dev/null +++ b/entc/integration/edgeschema/ent/user_create.go @@ -0,0 +1,468 @@ +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/edgeschema/ent/friendship" + "entgo.io/ent/entc/integration/edgeschema/ent/group" + "entgo.io/ent/entc/integration/edgeschema/ent/tweet" + "entgo.io/ent/entc/integration/edgeschema/ent/user" + "entgo.io/ent/entc/integration/edgeschema/ent/usergroup" + "entgo.io/ent/schema/field" +) + +// UserCreate is the builder for creating a User entity. +type UserCreate struct { + config + mutation *UserMutation + hooks []Hook +} + +// SetName sets the "name" field. +func (uc *UserCreate) SetName(s string) *UserCreate { + uc.mutation.SetName(s) + return uc +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (uc *UserCreate) SetNillableName(s *string) *UserCreate { + if s != nil { + uc.SetName(*s) + } + return uc +} + +// AddLikedTweetIDs adds the "liked_tweets" edge to the Tweet entity by IDs. +func (uc *UserCreate) AddLikedTweetIDs(ids ...int) *UserCreate { + uc.mutation.AddLikedTweetIDs(ids...) + return uc +} + +// AddLikedTweets adds the "liked_tweets" edges to the Tweet entity. +func (uc *UserCreate) AddLikedTweets(t ...*Tweet) *UserCreate { + ids := make([]int, len(t)) + for i := range t { + ids[i] = t[i].ID + } + return uc.AddLikedTweetIDs(ids...) +} + +// AddGroupIDs adds the "groups" edge to the Group entity by IDs. +func (uc *UserCreate) AddGroupIDs(ids ...int) *UserCreate { + uc.mutation.AddGroupIDs(ids...) + return uc +} + +// AddGroups adds the "groups" edges to the Group entity. +func (uc *UserCreate) AddGroups(g ...*Group) *UserCreate { + ids := make([]int, len(g)) + for i := range g { + ids[i] = g[i].ID + } + return uc.AddGroupIDs(ids...) +} + +// AddFriendIDs adds the "friends" edge to the User entity by IDs. +func (uc *UserCreate) AddFriendIDs(ids ...int) *UserCreate { + uc.mutation.AddFriendIDs(ids...) + return uc +} + +// AddFriends adds the "friends" edges to the User entity. +func (uc *UserCreate) AddFriends(u ...*User) *UserCreate { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return uc.AddFriendIDs(ids...) +} + +// AddRelativeIDs adds the "relatives" edge to the User entity by IDs. +func (uc *UserCreate) AddRelativeIDs(ids ...int) *UserCreate { + uc.mutation.AddRelativeIDs(ids...) + return uc +} + +// AddRelatives adds the "relatives" edges to the User entity. +func (uc *UserCreate) AddRelatives(u ...*User) *UserCreate { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return uc.AddRelativeIDs(ids...) +} + +// AddJoinedGroupIDs adds the "joined_groups" edge to the UserGroup entity by IDs. +func (uc *UserCreate) AddJoinedGroupIDs(ids ...int) *UserCreate { + uc.mutation.AddJoinedGroupIDs(ids...) + return uc +} + +// AddJoinedGroups adds the "joined_groups" edges to the UserGroup entity. +func (uc *UserCreate) AddJoinedGroups(u ...*UserGroup) *UserCreate { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return uc.AddJoinedGroupIDs(ids...) +} + +// AddFriendshipIDs adds the "friendships" edge to the Friendship entity by IDs. +func (uc *UserCreate) AddFriendshipIDs(ids ...int) *UserCreate { + uc.mutation.AddFriendshipIDs(ids...) + return uc +} + +// AddFriendships adds the "friendships" edges to the Friendship entity. +func (uc *UserCreate) AddFriendships(f ...*Friendship) *UserCreate { + ids := make([]int, len(f)) + for i := range f { + ids[i] = f[i].ID + } + return uc.AddFriendshipIDs(ids...) +} + +// Mutation returns the UserMutation object of the builder. +func (uc *UserCreate) Mutation() *UserMutation { + return uc.mutation +} + +// Save creates the User in the database. +func (uc *UserCreate) Save(ctx context.Context) (*User, error) { + var ( + err error + node *User + ) + uc.defaults() + if len(uc.hooks) == 0 { + if err = uc.check(); err != nil { + return nil, err + } + node, err = uc.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*UserMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err = uc.check(); err != nil { + return nil, err + } + uc.mutation = mutation + if node, err = uc.sqlSave(ctx); err != nil { + return nil, err + } + mutation.id = &node.ID + mutation.done = true + return node, err + }) + for i := len(uc.hooks) - 1; i >= 0; i-- { + if uc.hooks[i] == nil { + return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = uc.hooks[i](mut) + } + v, err := mut.Mutate(ctx, uc.mutation) + if err != nil { + return nil, err + } + nv, ok := v.(*User) + if !ok { + return nil, fmt.Errorf("unexpected node type %T returned from UserMutation", v) + } + node = nv + } + return node, err +} + +// SaveX calls Save and panics if Save returns an error. +func (uc *UserCreate) SaveX(ctx context.Context) *User { + v, err := uc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (uc *UserCreate) Exec(ctx context.Context) error { + _, err := uc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (uc *UserCreate) ExecX(ctx context.Context) { + if err := uc.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (uc *UserCreate) defaults() { + if _, ok := uc.mutation.Name(); !ok { + v := user.DefaultName + uc.mutation.SetName(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (uc *UserCreate) check() error { + if _, ok := uc.mutation.Name(); !ok { + return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "User.name"`)} + } + return nil +} + +func (uc *UserCreate) sqlSave(ctx context.Context) (*User, error) { + _node, _spec := uc.createSpec() + if err := sqlgraph.CreateNode(ctx, uc.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return nil, err + } + id := _spec.ID.Value.(int64) + _node.ID = int(id) + return _node, nil +} + +func (uc *UserCreate) createSpec() (*User, *sqlgraph.CreateSpec) { + var ( + _node = &User{config: uc.config} + _spec = &sqlgraph.CreateSpec{ + Table: user.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + } + ) + if value, ok := uc.mutation.Name(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: user.FieldName, + }) + _node.Name = value + } + if nodes := uc.mutation.LikedTweetsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.LikedTweetsTable, + Columns: user.LikedTweetsPrimaryKey, + 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 := &TweetLikeCreate{config: uc.config, mutation: newTweetLikeMutation(uc.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := uc.mutation.GroupsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.GroupsTable, + Columns: user.GroupsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: group.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + createE := &UserGroupCreate{config: uc.config, mutation: newUserGroupMutation(uc.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := uc.mutation.FriendsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.FriendsTable, + Columns: user.FriendsPrimaryKey, + Bidi: true, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + createE := &FriendshipCreate{config: uc.config, mutation: newFriendshipMutation(uc.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := uc.mutation.RelativesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.RelativesTable, + Columns: user.RelativesPrimaryKey, + Bidi: true, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + createE := &RelationshipCreate{config: uc.config, mutation: newRelationshipMutation(uc.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := uc.mutation.JoinedGroupsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: user.JoinedGroupsTable, + Columns: []string{user.JoinedGroupsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: usergroup.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := uc.mutation.FriendshipsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: user.FriendshipsTable, + Columns: []string{user.FriendshipsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: friendship.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// UserCreateBulk is the builder for creating many User entities in bulk. +type UserCreateBulk struct { + config + builders []*UserCreate +} + +// Save creates the User entities in the database. +func (ucb *UserCreateBulk) Save(ctx context.Context) ([]*User, error) { + specs := make([]*sqlgraph.CreateSpec, len(ucb.builders)) + nodes := make([]*User, len(ucb.builders)) + mutators := make([]Mutator, len(ucb.builders)) + for i := range ucb.builders { + func(i int, root context.Context) { + builder := ucb.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*UserMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + nodes[i], specs[i] = builder.createSpec() + var err error + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, ucb.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, ucb.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + 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, ucb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (ucb *UserCreateBulk) SaveX(ctx context.Context) []*User { + v, err := ucb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (ucb *UserCreateBulk) Exec(ctx context.Context) error { + _, err := ucb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (ucb *UserCreateBulk) ExecX(ctx context.Context) { + if err := ucb.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/entc/integration/edgeschema/ent/user_delete.go b/entc/integration/edgeschema/ent/user_delete.go new file mode 100644 index 0000000000..22e4408d11 --- /dev/null +++ b/entc/integration/edgeschema/ent/user_delete.go @@ -0,0 +1,111 @@ +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "fmt" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/edgeschema/ent/predicate" + "entgo.io/ent/entc/integration/edgeschema/ent/user" + "entgo.io/ent/schema/field" +) + +// UserDelete is the builder for deleting a User entity. +type UserDelete struct { + config + hooks []Hook + mutation *UserMutation +} + +// Where appends a list predicates to the UserDelete builder. +func (ud *UserDelete) Where(ps ...predicate.User) *UserDelete { + ud.mutation.Where(ps...) + return ud +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (ud *UserDelete) Exec(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(ud.hooks) == 0 { + affected, err = ud.sqlExec(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*UserMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + ud.mutation = mutation + affected, err = ud.sqlExec(ctx) + mutation.done = true + return affected, err + }) + for i := len(ud.hooks) - 1; i >= 0; i-- { + if ud.hooks[i] == nil { + return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = ud.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, ud.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// ExecX is like Exec, but panics if an error occurs. +func (ud *UserDelete) ExecX(ctx context.Context) int { + n, err := ud.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (ud *UserDelete) sqlExec(ctx context.Context) (int, error) { + _spec := &sqlgraph.DeleteSpec{ + Node: &sqlgraph.NodeSpec{ + Table: user.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + if ps := ud.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return sqlgraph.DeleteNodes(ctx, ud.driver, _spec) +} + +// UserDeleteOne is the builder for deleting a single User entity. +type UserDeleteOne struct { + ud *UserDelete +} + +// Exec executes the deletion query. +func (udo *UserDeleteOne) Exec(ctx context.Context) error { + n, err := udo.ud.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{user.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (udo *UserDeleteOne) ExecX(ctx context.Context) { + udo.ud.ExecX(ctx) +} diff --git a/entc/integration/edgeschema/ent/user_query.go b/entc/integration/edgeschema/ent/user_query.go new file mode 100644 index 0000000000..0dcfd3bc05 --- /dev/null +++ b/entc/integration/edgeschema/ent/user_query.go @@ -0,0 +1,1140 @@ +// Code generated by entc, 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/friendship" + "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/tweet" + "entgo.io/ent/entc/integration/edgeschema/ent/tweetlike" + "entgo.io/ent/entc/integration/edgeschema/ent/user" + "entgo.io/ent/entc/integration/edgeschema/ent/usergroup" + "entgo.io/ent/schema/field" +) + +// UserQuery is the builder for querying User entities. +type UserQuery struct { + config + limit *int + offset *int + unique *bool + order []OrderFunc + fields []string + predicates []predicate.User + // eager-loading edges. + withLikedTweets *TweetQuery + withGroups *GroupQuery + withFriends *UserQuery + withRelatives *UserQuery + withLikes *TweetLikeQuery + withJoinedGroups *UserGroupQuery + withFriendships *FriendshipQuery + withRelationship *RelationshipQuery + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the UserQuery builder. +func (uq *UserQuery) Where(ps ...predicate.User) *UserQuery { + uq.predicates = append(uq.predicates, ps...) + return uq +} + +// Limit adds a limit step to the query. +func (uq *UserQuery) Limit(limit int) *UserQuery { + uq.limit = &limit + return uq +} + +// Offset adds an offset step to the query. +func (uq *UserQuery) Offset(offset int) *UserQuery { + uq.offset = &offset + return uq +} + +// Unique configures the query builder to filter duplicate records on query. +// By default, unique is set to true, and can be disabled using this method. +func (uq *UserQuery) Unique(unique bool) *UserQuery { + uq.unique = &unique + return uq +} + +// Order adds an order step to the query. +func (uq *UserQuery) Order(o ...OrderFunc) *UserQuery { + uq.order = append(uq.order, o...) + return uq +} + +// QueryLikedTweets chains the current query on the "liked_tweets" edge. +func (uq *UserQuery) QueryLikedTweets() *TweetQuery { + query := &TweetQuery{config: uq.config} + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := uq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := uq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(user.Table, user.FieldID, selector), + sqlgraph.To(tweet.Table, tweet.FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, user.LikedTweetsTable, user.LikedTweetsPrimaryKey...), + ) + fromU = sqlgraph.SetNeighbors(uq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryGroups chains the current query on the "groups" edge. +func (uq *UserQuery) QueryGroups() *GroupQuery { + query := &GroupQuery{config: uq.config} + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := uq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := uq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(user.Table, user.FieldID, selector), + sqlgraph.To(group.Table, group.FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, user.GroupsTable, user.GroupsPrimaryKey...), + ) + fromU = sqlgraph.SetNeighbors(uq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryFriends chains the current query on the "friends" edge. +func (uq *UserQuery) QueryFriends() *UserQuery { + query := &UserQuery{config: uq.config} + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := uq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := uq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(user.Table, user.FieldID, selector), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, user.FriendsTable, user.FriendsPrimaryKey...), + ) + fromU = sqlgraph.SetNeighbors(uq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryRelatives chains the current query on the "relatives" edge. +func (uq *UserQuery) QueryRelatives() *UserQuery { + query := &UserQuery{config: uq.config} + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := uq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := uq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(user.Table, user.FieldID, selector), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, user.RelativesTable, user.RelativesPrimaryKey...), + ) + fromU = sqlgraph.SetNeighbors(uq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryLikes chains the current query on the "likes" edge. +func (uq *UserQuery) QueryLikes() *TweetLikeQuery { + query := &TweetLikeQuery{config: uq.config} + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := uq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := uq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(user.Table, user.FieldID, selector), + sqlgraph.To(tweetlike.Table, tweetlike.UserColumn), + sqlgraph.Edge(sqlgraph.O2M, true, user.LikesTable, user.LikesColumn), + ) + fromU = sqlgraph.SetNeighbors(uq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryJoinedGroups chains the current query on the "joined_groups" edge. +func (uq *UserQuery) QueryJoinedGroups() *UserGroupQuery { + query := &UserGroupQuery{config: uq.config} + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := uq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := uq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(user.Table, user.FieldID, selector), + sqlgraph.To(usergroup.Table, usergroup.FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, user.JoinedGroupsTable, user.JoinedGroupsColumn), + ) + fromU = sqlgraph.SetNeighbors(uq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryFriendships chains the current query on the "friendships" edge. +func (uq *UserQuery) QueryFriendships() *FriendshipQuery { + query := &FriendshipQuery{config: uq.config} + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := uq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := uq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(user.Table, user.FieldID, selector), + sqlgraph.To(friendship.Table, friendship.FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, user.FriendshipsTable, user.FriendshipsColumn), + ) + fromU = sqlgraph.SetNeighbors(uq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryRelationship chains the current query on the "relationship" edge. +func (uq *UserQuery) QueryRelationship() *RelationshipQuery { + query := &RelationshipQuery{config: uq.config} + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := uq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := uq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(user.Table, user.FieldID, selector), + sqlgraph.To(relationship.Table, relationship.UserColumn), + sqlgraph.Edge(sqlgraph.O2M, true, user.RelationshipTable, user.RelationshipColumn), + ) + fromU = sqlgraph.SetNeighbors(uq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first User entity from the query. +// Returns a *NotFoundError when no User was found. +func (uq *UserQuery) First(ctx context.Context) (*User, error) { + nodes, err := uq.Limit(1).All(ctx) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{user.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (uq *UserQuery) FirstX(ctx context.Context) *User { + node, err := uq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first User ID from the query. +// Returns a *NotFoundError when no User ID was found. +func (uq *UserQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = uq.Limit(1).IDs(ctx); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{user.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (uq *UserQuery) FirstIDX(ctx context.Context) int { + id, err := uq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single User entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one User entity is found. +// Returns a *NotFoundError when no User entities are found. +func (uq *UserQuery) Only(ctx context.Context) (*User, error) { + nodes, err := uq.Limit(2).All(ctx) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{user.Label} + default: + return nil, &NotSingularError{user.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (uq *UserQuery) OnlyX(ctx context.Context) *User { + node, err := uq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only User ID in the query. +// Returns a *NotSingularError when more than one User ID is found. +// Returns a *NotFoundError when no entities are found. +func (uq *UserQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = uq.Limit(2).IDs(ctx); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{user.Label} + default: + err = &NotSingularError{user.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (uq *UserQuery) OnlyIDX(ctx context.Context) int { + id, err := uq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of Users. +func (uq *UserQuery) All(ctx context.Context) ([]*User, error) { + if err := uq.prepareQuery(ctx); err != nil { + return nil, err + } + return uq.sqlAll(ctx) +} + +// AllX is like All, but panics if an error occurs. +func (uq *UserQuery) AllX(ctx context.Context) []*User { + nodes, err := uq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of User IDs. +func (uq *UserQuery) IDs(ctx context.Context) ([]int, error) { + var ids []int + if err := uq.Select(user.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (uq *UserQuery) IDsX(ctx context.Context) []int { + ids, err := uq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (uq *UserQuery) Count(ctx context.Context) (int, error) { + if err := uq.prepareQuery(ctx); err != nil { + return 0, err + } + return uq.sqlCount(ctx) +} + +// CountX is like Count, but panics if an error occurs. +func (uq *UserQuery) CountX(ctx context.Context) int { + count, err := uq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (uq *UserQuery) Exist(ctx context.Context) (bool, error) { + if err := uq.prepareQuery(ctx); err != nil { + return false, err + } + return uq.sqlExist(ctx) +} + +// ExistX is like Exist, but panics if an error occurs. +func (uq *UserQuery) ExistX(ctx context.Context) bool { + exist, err := uq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the UserQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (uq *UserQuery) Clone() *UserQuery { + if uq == nil { + return nil + } + return &UserQuery{ + config: uq.config, + limit: uq.limit, + offset: uq.offset, + order: append([]OrderFunc{}, uq.order...), + predicates: append([]predicate.User{}, uq.predicates...), + withLikedTweets: uq.withLikedTweets.Clone(), + withGroups: uq.withGroups.Clone(), + withFriends: uq.withFriends.Clone(), + withRelatives: uq.withRelatives.Clone(), + withLikes: uq.withLikes.Clone(), + withJoinedGroups: uq.withJoinedGroups.Clone(), + withFriendships: uq.withFriendships.Clone(), + withRelationship: uq.withRelationship.Clone(), + // clone intermediate query. + sql: uq.sql.Clone(), + path: uq.path, + unique: uq.unique, + } +} + +// WithLikedTweets tells the query-builder to eager-load the nodes that are connected to +// the "liked_tweets" edge. The optional arguments are used to configure the query builder of the edge. +func (uq *UserQuery) WithLikedTweets(opts ...func(*TweetQuery)) *UserQuery { + query := &TweetQuery{config: uq.config} + for _, opt := range opts { + opt(query) + } + uq.withLikedTweets = query + return uq +} + +// WithGroups tells the query-builder to eager-load the nodes that are connected to +// the "groups" edge. The optional arguments are used to configure the query builder of the edge. +func (uq *UserQuery) WithGroups(opts ...func(*GroupQuery)) *UserQuery { + query := &GroupQuery{config: uq.config} + for _, opt := range opts { + opt(query) + } + uq.withGroups = query + return uq +} + +// WithFriends tells the query-builder to eager-load the nodes that are connected to +// the "friends" edge. The optional arguments are used to configure the query builder of the edge. +func (uq *UserQuery) WithFriends(opts ...func(*UserQuery)) *UserQuery { + query := &UserQuery{config: uq.config} + for _, opt := range opts { + opt(query) + } + uq.withFriends = query + return uq +} + +// WithRelatives tells the query-builder to eager-load the nodes that are connected to +// the "relatives" edge. The optional arguments are used to configure the query builder of the edge. +func (uq *UserQuery) WithRelatives(opts ...func(*UserQuery)) *UserQuery { + query := &UserQuery{config: uq.config} + for _, opt := range opts { + opt(query) + } + uq.withRelatives = query + return uq +} + +// 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 (uq *UserQuery) WithLikes(opts ...func(*TweetLikeQuery)) *UserQuery { + query := &TweetLikeQuery{config: uq.config} + for _, opt := range opts { + opt(query) + } + uq.withLikes = query + return uq +} + +// WithJoinedGroups tells the query-builder to eager-load the nodes that are connected to +// the "joined_groups" edge. The optional arguments are used to configure the query builder of the edge. +func (uq *UserQuery) WithJoinedGroups(opts ...func(*UserGroupQuery)) *UserQuery { + query := &UserGroupQuery{config: uq.config} + for _, opt := range opts { + opt(query) + } + uq.withJoinedGroups = query + return uq +} + +// WithFriendships tells the query-builder to eager-load the nodes that are connected to +// the "friendships" edge. The optional arguments are used to configure the query builder of the edge. +func (uq *UserQuery) WithFriendships(opts ...func(*FriendshipQuery)) *UserQuery { + query := &FriendshipQuery{config: uq.config} + for _, opt := range opts { + opt(query) + } + uq.withFriendships = query + return uq +} + +// WithRelationship tells the query-builder to eager-load the nodes that are connected to +// the "relationship" edge. The optional arguments are used to configure the query builder of the edge. +func (uq *UserQuery) WithRelationship(opts ...func(*RelationshipQuery)) *UserQuery { + query := &RelationshipQuery{config: uq.config} + for _, opt := range opts { + opt(query) + } + uq.withRelationship = query + return uq +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// Name string `json:"name,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.User.Query(). +// GroupBy(user.FieldName). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +// +func (uq *UserQuery) GroupBy(field string, fields ...string) *UserGroupBy { + grbuild := &UserGroupBy{config: uq.config} + grbuild.fields = append([]string{field}, fields...) + grbuild.path = func(ctx context.Context) (prev *sql.Selector, err error) { + if err := uq.prepareQuery(ctx); err != nil { + return nil, err + } + return uq.sqlQuery(ctx), nil + } + grbuild.label = user.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 { +// Name string `json:"name,omitempty"` +// } +// +// client.User.Query(). +// Select(user.FieldName). +// Scan(ctx, &v) +// +func (uq *UserQuery) Select(fields ...string) *UserSelect { + uq.fields = append(uq.fields, fields...) + selbuild := &UserSelect{UserQuery: uq} + selbuild.label = user.Label + selbuild.flds, selbuild.scan = &uq.fields, selbuild.Scan + return selbuild +} + +func (uq *UserQuery) prepareQuery(ctx context.Context) error { + for _, f := range uq.fields { + if !user.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if uq.path != nil { + prev, err := uq.path(ctx) + if err != nil { + return err + } + uq.sql = prev + } + return nil +} + +func (uq *UserQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*User, error) { + var ( + nodes = []*User{} + _spec = uq.querySpec() + loadedTypes = [8]bool{ + uq.withLikedTweets != nil, + uq.withGroups != nil, + uq.withFriends != nil, + uq.withRelatives != nil, + uq.withLikes != nil, + uq.withJoinedGroups != nil, + uq.withFriendships != nil, + uq.withRelationship != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]interface{}, error) { + return (*User).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []interface{}) error { + node := &User{config: uq.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, uq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + + if query := uq.withLikedTweets; query != nil { + edgeids := make([]driver.Value, len(nodes)) + byid := make(map[int]*User) + nids := make(map[int]map[*User]struct{}) + for i, node := range nodes { + edgeids[i] = node.ID + byid[node.ID] = node + node.Edges.LikedTweets = []*Tweet{} + } + query.Where(func(s *sql.Selector) { + joinT := sql.Table(user.LikedTweetsTable) + s.Join(joinT).On(s.C(tweet.FieldID), joinT.C(user.LikedTweetsPrimaryKey[1])) + s.Where(sql.InValues(joinT.C(user.LikedTweetsPrimaryKey[0]), edgeids...)) + columns := s.SelectedColumns() + s.Select(joinT.C(user.LikedTweetsPrimaryKey[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[*User]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 "liked_tweets" node returned %v`, n.ID) + } + for kn := range nodes { + kn.Edges.LikedTweets = append(kn.Edges.LikedTweets, n) + } + } + } + + if query := uq.withGroups; query != nil { + edgeids := make([]driver.Value, len(nodes)) + byid := make(map[int]*User) + nids := make(map[int]map[*User]struct{}) + for i, node := range nodes { + edgeids[i] = node.ID + byid[node.ID] = node + node.Edges.Groups = []*Group{} + } + query.Where(func(s *sql.Selector) { + joinT := sql.Table(user.GroupsTable) + s.Join(joinT).On(s.C(group.FieldID), joinT.C(user.GroupsPrimaryKey[1])) + s.Where(sql.InValues(joinT.C(user.GroupsPrimaryKey[0]), edgeids...)) + columns := s.SelectedColumns() + s.Select(joinT.C(user.GroupsPrimaryKey[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[*User]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 "groups" node returned %v`, n.ID) + } + for kn := range nodes { + kn.Edges.Groups = append(kn.Edges.Groups, n) + } + } + } + + if query := uq.withFriends; query != nil { + edgeids := make([]driver.Value, len(nodes)) + byid := make(map[int]*User) + nids := make(map[int]map[*User]struct{}) + for i, node := range nodes { + edgeids[i] = node.ID + byid[node.ID] = node + node.Edges.Friends = []*User{} + } + query.Where(func(s *sql.Selector) { + joinT := sql.Table(user.FriendsTable) + s.Join(joinT).On(s.C(user.FieldID), joinT.C(user.FriendsPrimaryKey[1])) + s.Where(sql.InValues(joinT.C(user.FriendsPrimaryKey[0]), edgeids...)) + columns := s.SelectedColumns() + s.Select(joinT.C(user.FriendsPrimaryKey[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[*User]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 "friends" node returned %v`, n.ID) + } + for kn := range nodes { + kn.Edges.Friends = append(kn.Edges.Friends, n) + } + } + } + + if query := uq.withRelatives; query != nil { + edgeids := make([]driver.Value, len(nodes)) + byid := make(map[int]*User) + nids := make(map[int]map[*User]struct{}) + for i, node := range nodes { + edgeids[i] = node.ID + byid[node.ID] = node + node.Edges.Relatives = []*User{} + } + query.Where(func(s *sql.Selector) { + joinT := sql.Table(user.RelativesTable) + s.Join(joinT).On(s.C(user.FieldID), joinT.C(user.RelativesPrimaryKey[1])) + s.Where(sql.InValues(joinT.C(user.RelativesPrimaryKey[0]), edgeids...)) + columns := s.SelectedColumns() + s.Select(joinT.C(user.RelativesPrimaryKey[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[*User]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 "relatives" node returned %v`, n.ID) + } + for kn := range nodes { + kn.Edges.Relatives = append(kn.Edges.Relatives, n) + } + } + } + + if query := uq.withLikes; query != nil { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[int]*User) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + nodes[i].Edges.Likes = []*TweetLike{} + } + query.Where(predicate.TweetLike(func(s *sql.Selector) { + s.Where(sql.InValues(user.LikesColumn, fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return nil, err + } + for _, n := range neighbors { + fk := n.UserID + node, ok := nodeids[fk] + if !ok { + return nil, fmt.Errorf(`unexpected foreign-key "user_id" returned %v for node %v`, fk, n) + } + node.Edges.Likes = append(node.Edges.Likes, n) + } + } + + if query := uq.withJoinedGroups; query != nil { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[int]*User) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + nodes[i].Edges.JoinedGroups = []*UserGroup{} + } + query.Where(predicate.UserGroup(func(s *sql.Selector) { + s.Where(sql.InValues(user.JoinedGroupsColumn, fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return nil, err + } + for _, n := range neighbors { + fk := n.UserID + node, ok := nodeids[fk] + if !ok { + return nil, fmt.Errorf(`unexpected foreign-key "user_id" returned %v for node %v`, fk, n.ID) + } + node.Edges.JoinedGroups = append(node.Edges.JoinedGroups, n) + } + } + + if query := uq.withFriendships; query != nil { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[int]*User) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + nodes[i].Edges.Friendships = []*Friendship{} + } + query.Where(predicate.Friendship(func(s *sql.Selector) { + s.Where(sql.InValues(user.FriendshipsColumn, fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return nil, err + } + for _, n := range neighbors { + fk := n.UserID + node, ok := nodeids[fk] + if !ok { + return nil, fmt.Errorf(`unexpected foreign-key "user_id" returned %v for node %v`, fk, n.ID) + } + node.Edges.Friendships = append(node.Edges.Friendships, n) + } + } + + if query := uq.withRelationship; query != nil { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[int]*User) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + nodes[i].Edges.Relationship = []*Relationship{} + } + query.Where(predicate.Relationship(func(s *sql.Selector) { + s.Where(sql.InValues(user.RelationshipColumn, fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return nil, err + } + for _, n := range neighbors { + fk := n.UserID + node, ok := nodeids[fk] + if !ok { + return nil, fmt.Errorf(`unexpected foreign-key "user_id" returned %v for node %v`, fk, n) + } + node.Edges.Relationship = append(node.Edges.Relationship, n) + } + } + + return nodes, nil +} + +func (uq *UserQuery) sqlCount(ctx context.Context) (int, error) { + _spec := uq.querySpec() + _spec.Node.Columns = uq.fields + if len(uq.fields) > 0 { + _spec.Unique = uq.unique != nil && *uq.unique + } + return sqlgraph.CountNodes(ctx, uq.driver, _spec) +} + +func (uq *UserQuery) sqlExist(ctx context.Context) (bool, error) { + n, err := uq.sqlCount(ctx) + if err != nil { + return false, fmt.Errorf("ent: check existence: %w", err) + } + return n > 0, nil +} + +func (uq *UserQuery) querySpec() *sqlgraph.QuerySpec { + _spec := &sqlgraph.QuerySpec{ + Node: &sqlgraph.NodeSpec{ + Table: user.Table, + Columns: user.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + From: uq.sql, + Unique: true, + } + if unique := uq.unique; unique != nil { + _spec.Unique = *unique + } + if fields := uq.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, user.FieldID) + for i := range fields { + if fields[i] != user.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := uq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := uq.limit; limit != nil { + _spec.Limit = *limit + } + if offset := uq.offset; offset != nil { + _spec.Offset = *offset + } + if ps := uq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (uq *UserQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(uq.driver.Dialect()) + t1 := builder.Table(user.Table) + columns := uq.fields + if len(columns) == 0 { + columns = user.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if uq.sql != nil { + selector = uq.sql + selector.Select(selector.Columns(columns...)...) + } + if uq.unique != nil && *uq.unique { + selector.Distinct() + } + for _, p := range uq.predicates { + p(selector) + } + for _, p := range uq.order { + p(selector) + } + if offset := uq.offset; offset != nil { + // limit is mandatory for offset clause. We start + // with default value, and override it below if needed. + selector.Offset(*offset).Limit(math.MaxInt32) + } + if limit := uq.limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// UserGroupBy is the group-by builder for User entities. +type UserGroupBy struct { + config + 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 (ugb *UserGroupBy) Aggregate(fns ...AggregateFunc) *UserGroupBy { + ugb.fns = append(ugb.fns, fns...) + return ugb +} + +// Scan applies the group-by query and scans the result into the given value. +func (ugb *UserGroupBy) Scan(ctx context.Context, v interface{}) error { + query, err := ugb.path(ctx) + if err != nil { + return err + } + ugb.sql = query + return ugb.sqlScan(ctx, v) +} + +func (ugb *UserGroupBy) sqlScan(ctx context.Context, v interface{}) error { + for _, f := range ugb.fields { + if !user.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)} + } + } + selector := ugb.sqlQuery() + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := ugb.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +func (ugb *UserGroupBy) sqlQuery() *sql.Selector { + selector := ugb.sql.Select() + aggregation := make([]string, 0, len(ugb.fns)) + for _, fn := range ugb.fns { + aggregation = append(aggregation, fn(selector)) + } + // If no columns were selected in a custom aggregation function, the default + // selection is the fields used for "group-by", and the aggregation functions. + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(ugb.fields)+len(ugb.fns)) + for _, f := range ugb.fields { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + return selector.GroupBy(selector.Columns(ugb.fields...)...) +} + +// UserSelect is the builder for selecting fields of User entities. +type UserSelect struct { + *UserQuery + selector + // intermediate query (i.e. traversal path). + sql *sql.Selector +} + +// Scan applies the selector query and scans the result into the given value. +func (us *UserSelect) Scan(ctx context.Context, v interface{}) error { + if err := us.prepareQuery(ctx); err != nil { + return err + } + us.sql = us.UserQuery.sqlQuery(ctx) + return us.sqlScan(ctx, v) +} + +func (us *UserSelect) sqlScan(ctx context.Context, v interface{}) error { + rows := &sql.Rows{} + query, args := us.sql.Query() + if err := us.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/entc/integration/edgeschema/ent/user_update.go b/entc/integration/edgeschema/ent/user_update.go new file mode 100644 index 0000000000..ee7cf3fc7d --- /dev/null +++ b/entc/integration/edgeschema/ent/user_update.go @@ -0,0 +1,1467 @@ +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/edgeschema/ent/friendship" + "entgo.io/ent/entc/integration/edgeschema/ent/group" + "entgo.io/ent/entc/integration/edgeschema/ent/predicate" + "entgo.io/ent/entc/integration/edgeschema/ent/tweet" + "entgo.io/ent/entc/integration/edgeschema/ent/user" + "entgo.io/ent/entc/integration/edgeschema/ent/usergroup" + "entgo.io/ent/schema/field" +) + +// UserUpdate is the builder for updating User entities. +type UserUpdate struct { + config + hooks []Hook + mutation *UserMutation +} + +// Where appends a list predicates to the UserUpdate builder. +func (uu *UserUpdate) Where(ps ...predicate.User) *UserUpdate { + uu.mutation.Where(ps...) + return uu +} + +// SetName sets the "name" field. +func (uu *UserUpdate) SetName(s string) *UserUpdate { + uu.mutation.SetName(s) + return uu +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (uu *UserUpdate) SetNillableName(s *string) *UserUpdate { + if s != nil { + uu.SetName(*s) + } + return uu +} + +// AddLikedTweetIDs adds the "liked_tweets" edge to the Tweet entity by IDs. +func (uu *UserUpdate) AddLikedTweetIDs(ids ...int) *UserUpdate { + uu.mutation.AddLikedTweetIDs(ids...) + return uu +} + +// AddLikedTweets adds the "liked_tweets" edges to the Tweet entity. +func (uu *UserUpdate) AddLikedTweets(t ...*Tweet) *UserUpdate { + ids := make([]int, len(t)) + for i := range t { + ids[i] = t[i].ID + } + return uu.AddLikedTweetIDs(ids...) +} + +// AddGroupIDs adds the "groups" edge to the Group entity by IDs. +func (uu *UserUpdate) AddGroupIDs(ids ...int) *UserUpdate { + uu.mutation.AddGroupIDs(ids...) + return uu +} + +// AddGroups adds the "groups" edges to the Group entity. +func (uu *UserUpdate) AddGroups(g ...*Group) *UserUpdate { + ids := make([]int, len(g)) + for i := range g { + ids[i] = g[i].ID + } + return uu.AddGroupIDs(ids...) +} + +// AddFriendIDs adds the "friends" edge to the User entity by IDs. +func (uu *UserUpdate) AddFriendIDs(ids ...int) *UserUpdate { + uu.mutation.AddFriendIDs(ids...) + return uu +} + +// AddFriends adds the "friends" edges to the User entity. +func (uu *UserUpdate) AddFriends(u ...*User) *UserUpdate { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return uu.AddFriendIDs(ids...) +} + +// AddRelativeIDs adds the "relatives" edge to the User entity by IDs. +func (uu *UserUpdate) AddRelativeIDs(ids ...int) *UserUpdate { + uu.mutation.AddRelativeIDs(ids...) + return uu +} + +// AddRelatives adds the "relatives" edges to the User entity. +func (uu *UserUpdate) AddRelatives(u ...*User) *UserUpdate { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return uu.AddRelativeIDs(ids...) +} + +// AddJoinedGroupIDs adds the "joined_groups" edge to the UserGroup entity by IDs. +func (uu *UserUpdate) AddJoinedGroupIDs(ids ...int) *UserUpdate { + uu.mutation.AddJoinedGroupIDs(ids...) + return uu +} + +// AddJoinedGroups adds the "joined_groups" edges to the UserGroup entity. +func (uu *UserUpdate) AddJoinedGroups(u ...*UserGroup) *UserUpdate { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return uu.AddJoinedGroupIDs(ids...) +} + +// AddFriendshipIDs adds the "friendships" edge to the Friendship entity by IDs. +func (uu *UserUpdate) AddFriendshipIDs(ids ...int) *UserUpdate { + uu.mutation.AddFriendshipIDs(ids...) + return uu +} + +// AddFriendships adds the "friendships" edges to the Friendship entity. +func (uu *UserUpdate) AddFriendships(f ...*Friendship) *UserUpdate { + ids := make([]int, len(f)) + for i := range f { + ids[i] = f[i].ID + } + return uu.AddFriendshipIDs(ids...) +} + +// Mutation returns the UserMutation object of the builder. +func (uu *UserUpdate) Mutation() *UserMutation { + return uu.mutation +} + +// ClearLikedTweets clears all "liked_tweets" edges to the Tweet entity. +func (uu *UserUpdate) ClearLikedTweets() *UserUpdate { + uu.mutation.ClearLikedTweets() + return uu +} + +// RemoveLikedTweetIDs removes the "liked_tweets" edge to Tweet entities by IDs. +func (uu *UserUpdate) RemoveLikedTweetIDs(ids ...int) *UserUpdate { + uu.mutation.RemoveLikedTweetIDs(ids...) + return uu +} + +// RemoveLikedTweets removes "liked_tweets" edges to Tweet entities. +func (uu *UserUpdate) RemoveLikedTweets(t ...*Tweet) *UserUpdate { + ids := make([]int, len(t)) + for i := range t { + ids[i] = t[i].ID + } + return uu.RemoveLikedTweetIDs(ids...) +} + +// ClearGroups clears all "groups" edges to the Group entity. +func (uu *UserUpdate) ClearGroups() *UserUpdate { + uu.mutation.ClearGroups() + return uu +} + +// RemoveGroupIDs removes the "groups" edge to Group entities by IDs. +func (uu *UserUpdate) RemoveGroupIDs(ids ...int) *UserUpdate { + uu.mutation.RemoveGroupIDs(ids...) + return uu +} + +// RemoveGroups removes "groups" edges to Group entities. +func (uu *UserUpdate) RemoveGroups(g ...*Group) *UserUpdate { + ids := make([]int, len(g)) + for i := range g { + ids[i] = g[i].ID + } + return uu.RemoveGroupIDs(ids...) +} + +// ClearFriends clears all "friends" edges to the User entity. +func (uu *UserUpdate) ClearFriends() *UserUpdate { + uu.mutation.ClearFriends() + return uu +} + +// RemoveFriendIDs removes the "friends" edge to User entities by IDs. +func (uu *UserUpdate) RemoveFriendIDs(ids ...int) *UserUpdate { + uu.mutation.RemoveFriendIDs(ids...) + return uu +} + +// RemoveFriends removes "friends" edges to User entities. +func (uu *UserUpdate) RemoveFriends(u ...*User) *UserUpdate { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return uu.RemoveFriendIDs(ids...) +} + +// ClearRelatives clears all "relatives" edges to the User entity. +func (uu *UserUpdate) ClearRelatives() *UserUpdate { + uu.mutation.ClearRelatives() + return uu +} + +// RemoveRelativeIDs removes the "relatives" edge to User entities by IDs. +func (uu *UserUpdate) RemoveRelativeIDs(ids ...int) *UserUpdate { + uu.mutation.RemoveRelativeIDs(ids...) + return uu +} + +// RemoveRelatives removes "relatives" edges to User entities. +func (uu *UserUpdate) RemoveRelatives(u ...*User) *UserUpdate { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return uu.RemoveRelativeIDs(ids...) +} + +// ClearJoinedGroups clears all "joined_groups" edges to the UserGroup entity. +func (uu *UserUpdate) ClearJoinedGroups() *UserUpdate { + uu.mutation.ClearJoinedGroups() + return uu +} + +// RemoveJoinedGroupIDs removes the "joined_groups" edge to UserGroup entities by IDs. +func (uu *UserUpdate) RemoveJoinedGroupIDs(ids ...int) *UserUpdate { + uu.mutation.RemoveJoinedGroupIDs(ids...) + return uu +} + +// RemoveJoinedGroups removes "joined_groups" edges to UserGroup entities. +func (uu *UserUpdate) RemoveJoinedGroups(u ...*UserGroup) *UserUpdate { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return uu.RemoveJoinedGroupIDs(ids...) +} + +// ClearFriendships clears all "friendships" edges to the Friendship entity. +func (uu *UserUpdate) ClearFriendships() *UserUpdate { + uu.mutation.ClearFriendships() + return uu +} + +// RemoveFriendshipIDs removes the "friendships" edge to Friendship entities by IDs. +func (uu *UserUpdate) RemoveFriendshipIDs(ids ...int) *UserUpdate { + uu.mutation.RemoveFriendshipIDs(ids...) + return uu +} + +// RemoveFriendships removes "friendships" edges to Friendship entities. +func (uu *UserUpdate) RemoveFriendships(f ...*Friendship) *UserUpdate { + ids := make([]int, len(f)) + for i := range f { + ids[i] = f[i].ID + } + return uu.RemoveFriendshipIDs(ids...) +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (uu *UserUpdate) Save(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(uu.hooks) == 0 { + affected, err = uu.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*UserMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + uu.mutation = mutation + affected, err = uu.sqlSave(ctx) + mutation.done = true + return affected, err + }) + for i := len(uu.hooks) - 1; i >= 0; i-- { + if uu.hooks[i] == nil { + return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = uu.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, uu.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// SaveX is like Save, but panics if an error occurs. +func (uu *UserUpdate) SaveX(ctx context.Context) int { + affected, err := uu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (uu *UserUpdate) Exec(ctx context.Context) error { + _, err := uu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (uu *UserUpdate) ExecX(ctx context.Context) { + if err := uu.Exec(ctx); err != nil { + panic(err) + } +} + +func (uu *UserUpdate) sqlSave(ctx context.Context) (n int, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: user.Table, + Columns: user.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + if ps := uu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := uu.mutation.Name(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: user.FieldName, + }) + } + if uu.mutation.LikedTweetsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.LikedTweetsTable, + Columns: user.LikedTweetsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: tweet.FieldID, + }, + }, + } + createE := &TweetLikeCreate{config: uu.config, mutation: newTweetLikeMutation(uu.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uu.mutation.RemovedLikedTweetsIDs(); len(nodes) > 0 && !uu.mutation.LikedTweetsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.LikedTweetsTable, + Columns: user.LikedTweetsPrimaryKey, + 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 := &TweetLikeCreate{config: uu.config, mutation: newTweetLikeMutation(uu.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uu.mutation.LikedTweetsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.LikedTweetsTable, + Columns: user.LikedTweetsPrimaryKey, + 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 := &TweetLikeCreate{config: uu.config, mutation: newTweetLikeMutation(uu.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if uu.mutation.GroupsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.GroupsTable, + Columns: user.GroupsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: group.FieldID, + }, + }, + } + createE := &UserGroupCreate{config: uu.config, mutation: newUserGroupMutation(uu.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uu.mutation.RemovedGroupsIDs(); len(nodes) > 0 && !uu.mutation.GroupsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.GroupsTable, + Columns: user.GroupsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: group.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + createE := &UserGroupCreate{config: uu.config, mutation: newUserGroupMutation(uu.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uu.mutation.GroupsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.GroupsTable, + Columns: user.GroupsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: group.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + createE := &UserGroupCreate{config: uu.config, mutation: newUserGroupMutation(uu.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if uu.mutation.FriendsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.FriendsTable, + Columns: user.FriendsPrimaryKey, + Bidi: true, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + createE := &FriendshipCreate{config: uu.config, mutation: newFriendshipMutation(uu.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uu.mutation.RemovedFriendsIDs(); len(nodes) > 0 && !uu.mutation.FriendsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.FriendsTable, + Columns: user.FriendsPrimaryKey, + Bidi: true, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + createE := &FriendshipCreate{config: uu.config, mutation: newFriendshipMutation(uu.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uu.mutation.FriendsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.FriendsTable, + Columns: user.FriendsPrimaryKey, + Bidi: true, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + createE := &FriendshipCreate{config: uu.config, mutation: newFriendshipMutation(uu.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if uu.mutation.RelativesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.RelativesTable, + Columns: user.RelativesPrimaryKey, + Bidi: true, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + createE := &RelationshipCreate{config: uu.config, mutation: newRelationshipMutation(uu.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uu.mutation.RemovedRelativesIDs(); len(nodes) > 0 && !uu.mutation.RelativesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.RelativesTable, + Columns: user.RelativesPrimaryKey, + Bidi: true, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + createE := &RelationshipCreate{config: uu.config, mutation: newRelationshipMutation(uu.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uu.mutation.RelativesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.RelativesTable, + Columns: user.RelativesPrimaryKey, + Bidi: true, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + createE := &RelationshipCreate{config: uu.config, mutation: newRelationshipMutation(uu.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if uu.mutation.JoinedGroupsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: user.JoinedGroupsTable, + Columns: []string{user.JoinedGroupsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: usergroup.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uu.mutation.RemovedJoinedGroupsIDs(); len(nodes) > 0 && !uu.mutation.JoinedGroupsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: user.JoinedGroupsTable, + Columns: []string{user.JoinedGroupsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: usergroup.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uu.mutation.JoinedGroupsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: user.JoinedGroupsTable, + Columns: []string{user.JoinedGroupsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: usergroup.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if uu.mutation.FriendshipsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: user.FriendshipsTable, + Columns: []string{user.FriendshipsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: friendship.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uu.mutation.RemovedFriendshipsIDs(); len(nodes) > 0 && !uu.mutation.FriendshipsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: user.FriendshipsTable, + Columns: []string{user.FriendshipsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: friendship.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uu.mutation.FriendshipsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: user.FriendshipsTable, + Columns: []string{user.FriendshipsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: friendship.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if n, err = sqlgraph.UpdateNodes(ctx, uu.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{user.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return 0, err + } + return n, nil +} + +// UserUpdateOne is the builder for updating a single User entity. +type UserUpdateOne struct { + config + fields []string + hooks []Hook + mutation *UserMutation +} + +// SetName sets the "name" field. +func (uuo *UserUpdateOne) SetName(s string) *UserUpdateOne { + uuo.mutation.SetName(s) + return uuo +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (uuo *UserUpdateOne) SetNillableName(s *string) *UserUpdateOne { + if s != nil { + uuo.SetName(*s) + } + return uuo +} + +// AddLikedTweetIDs adds the "liked_tweets" edge to the Tweet entity by IDs. +func (uuo *UserUpdateOne) AddLikedTweetIDs(ids ...int) *UserUpdateOne { + uuo.mutation.AddLikedTweetIDs(ids...) + return uuo +} + +// AddLikedTweets adds the "liked_tweets" edges to the Tweet entity. +func (uuo *UserUpdateOne) AddLikedTweets(t ...*Tweet) *UserUpdateOne { + ids := make([]int, len(t)) + for i := range t { + ids[i] = t[i].ID + } + return uuo.AddLikedTweetIDs(ids...) +} + +// AddGroupIDs adds the "groups" edge to the Group entity by IDs. +func (uuo *UserUpdateOne) AddGroupIDs(ids ...int) *UserUpdateOne { + uuo.mutation.AddGroupIDs(ids...) + return uuo +} + +// AddGroups adds the "groups" edges to the Group entity. +func (uuo *UserUpdateOne) AddGroups(g ...*Group) *UserUpdateOne { + ids := make([]int, len(g)) + for i := range g { + ids[i] = g[i].ID + } + return uuo.AddGroupIDs(ids...) +} + +// AddFriendIDs adds the "friends" edge to the User entity by IDs. +func (uuo *UserUpdateOne) AddFriendIDs(ids ...int) *UserUpdateOne { + uuo.mutation.AddFriendIDs(ids...) + return uuo +} + +// AddFriends adds the "friends" edges to the User entity. +func (uuo *UserUpdateOne) AddFriends(u ...*User) *UserUpdateOne { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return uuo.AddFriendIDs(ids...) +} + +// AddRelativeIDs adds the "relatives" edge to the User entity by IDs. +func (uuo *UserUpdateOne) AddRelativeIDs(ids ...int) *UserUpdateOne { + uuo.mutation.AddRelativeIDs(ids...) + return uuo +} + +// AddRelatives adds the "relatives" edges to the User entity. +func (uuo *UserUpdateOne) AddRelatives(u ...*User) *UserUpdateOne { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return uuo.AddRelativeIDs(ids...) +} + +// AddJoinedGroupIDs adds the "joined_groups" edge to the UserGroup entity by IDs. +func (uuo *UserUpdateOne) AddJoinedGroupIDs(ids ...int) *UserUpdateOne { + uuo.mutation.AddJoinedGroupIDs(ids...) + return uuo +} + +// AddJoinedGroups adds the "joined_groups" edges to the UserGroup entity. +func (uuo *UserUpdateOne) AddJoinedGroups(u ...*UserGroup) *UserUpdateOne { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return uuo.AddJoinedGroupIDs(ids...) +} + +// AddFriendshipIDs adds the "friendships" edge to the Friendship entity by IDs. +func (uuo *UserUpdateOne) AddFriendshipIDs(ids ...int) *UserUpdateOne { + uuo.mutation.AddFriendshipIDs(ids...) + return uuo +} + +// AddFriendships adds the "friendships" edges to the Friendship entity. +func (uuo *UserUpdateOne) AddFriendships(f ...*Friendship) *UserUpdateOne { + ids := make([]int, len(f)) + for i := range f { + ids[i] = f[i].ID + } + return uuo.AddFriendshipIDs(ids...) +} + +// Mutation returns the UserMutation object of the builder. +func (uuo *UserUpdateOne) Mutation() *UserMutation { + return uuo.mutation +} + +// ClearLikedTweets clears all "liked_tweets" edges to the Tweet entity. +func (uuo *UserUpdateOne) ClearLikedTweets() *UserUpdateOne { + uuo.mutation.ClearLikedTweets() + return uuo +} + +// RemoveLikedTweetIDs removes the "liked_tweets" edge to Tweet entities by IDs. +func (uuo *UserUpdateOne) RemoveLikedTweetIDs(ids ...int) *UserUpdateOne { + uuo.mutation.RemoveLikedTweetIDs(ids...) + return uuo +} + +// RemoveLikedTweets removes "liked_tweets" edges to Tweet entities. +func (uuo *UserUpdateOne) RemoveLikedTweets(t ...*Tweet) *UserUpdateOne { + ids := make([]int, len(t)) + for i := range t { + ids[i] = t[i].ID + } + return uuo.RemoveLikedTweetIDs(ids...) +} + +// ClearGroups clears all "groups" edges to the Group entity. +func (uuo *UserUpdateOne) ClearGroups() *UserUpdateOne { + uuo.mutation.ClearGroups() + return uuo +} + +// RemoveGroupIDs removes the "groups" edge to Group entities by IDs. +func (uuo *UserUpdateOne) RemoveGroupIDs(ids ...int) *UserUpdateOne { + uuo.mutation.RemoveGroupIDs(ids...) + return uuo +} + +// RemoveGroups removes "groups" edges to Group entities. +func (uuo *UserUpdateOne) RemoveGroups(g ...*Group) *UserUpdateOne { + ids := make([]int, len(g)) + for i := range g { + ids[i] = g[i].ID + } + return uuo.RemoveGroupIDs(ids...) +} + +// ClearFriends clears all "friends" edges to the User entity. +func (uuo *UserUpdateOne) ClearFriends() *UserUpdateOne { + uuo.mutation.ClearFriends() + return uuo +} + +// RemoveFriendIDs removes the "friends" edge to User entities by IDs. +func (uuo *UserUpdateOne) RemoveFriendIDs(ids ...int) *UserUpdateOne { + uuo.mutation.RemoveFriendIDs(ids...) + return uuo +} + +// RemoveFriends removes "friends" edges to User entities. +func (uuo *UserUpdateOne) RemoveFriends(u ...*User) *UserUpdateOne { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return uuo.RemoveFriendIDs(ids...) +} + +// ClearRelatives clears all "relatives" edges to the User entity. +func (uuo *UserUpdateOne) ClearRelatives() *UserUpdateOne { + uuo.mutation.ClearRelatives() + return uuo +} + +// RemoveRelativeIDs removes the "relatives" edge to User entities by IDs. +func (uuo *UserUpdateOne) RemoveRelativeIDs(ids ...int) *UserUpdateOne { + uuo.mutation.RemoveRelativeIDs(ids...) + return uuo +} + +// RemoveRelatives removes "relatives" edges to User entities. +func (uuo *UserUpdateOne) RemoveRelatives(u ...*User) *UserUpdateOne { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return uuo.RemoveRelativeIDs(ids...) +} + +// ClearJoinedGroups clears all "joined_groups" edges to the UserGroup entity. +func (uuo *UserUpdateOne) ClearJoinedGroups() *UserUpdateOne { + uuo.mutation.ClearJoinedGroups() + return uuo +} + +// RemoveJoinedGroupIDs removes the "joined_groups" edge to UserGroup entities by IDs. +func (uuo *UserUpdateOne) RemoveJoinedGroupIDs(ids ...int) *UserUpdateOne { + uuo.mutation.RemoveJoinedGroupIDs(ids...) + return uuo +} + +// RemoveJoinedGroups removes "joined_groups" edges to UserGroup entities. +func (uuo *UserUpdateOne) RemoveJoinedGroups(u ...*UserGroup) *UserUpdateOne { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return uuo.RemoveJoinedGroupIDs(ids...) +} + +// ClearFriendships clears all "friendships" edges to the Friendship entity. +func (uuo *UserUpdateOne) ClearFriendships() *UserUpdateOne { + uuo.mutation.ClearFriendships() + return uuo +} + +// RemoveFriendshipIDs removes the "friendships" edge to Friendship entities by IDs. +func (uuo *UserUpdateOne) RemoveFriendshipIDs(ids ...int) *UserUpdateOne { + uuo.mutation.RemoveFriendshipIDs(ids...) + return uuo +} + +// RemoveFriendships removes "friendships" edges to Friendship entities. +func (uuo *UserUpdateOne) RemoveFriendships(f ...*Friendship) *UserUpdateOne { + ids := make([]int, len(f)) + for i := range f { + ids[i] = f[i].ID + } + return uuo.RemoveFriendshipIDs(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 (uuo *UserUpdateOne) Select(field string, fields ...string) *UserUpdateOne { + uuo.fields = append([]string{field}, fields...) + return uuo +} + +// Save executes the query and returns the updated User entity. +func (uuo *UserUpdateOne) Save(ctx context.Context) (*User, error) { + var ( + err error + node *User + ) + if len(uuo.hooks) == 0 { + node, err = uuo.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*UserMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + uuo.mutation = mutation + node, err = uuo.sqlSave(ctx) + mutation.done = true + return node, err + }) + for i := len(uuo.hooks) - 1; i >= 0; i-- { + if uuo.hooks[i] == nil { + return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = uuo.hooks[i](mut) + } + v, err := mut.Mutate(ctx, uuo.mutation) + if err != nil { + return nil, err + } + nv, ok := v.(*User) + if !ok { + return nil, fmt.Errorf("unexpected node type %T returned from UserMutation", v) + } + node = nv + } + return node, err +} + +// SaveX is like Save, but panics if an error occurs. +func (uuo *UserUpdateOne) SaveX(ctx context.Context) *User { + node, err := uuo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (uuo *UserUpdateOne) Exec(ctx context.Context) error { + _, err := uuo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (uuo *UserUpdateOne) ExecX(ctx context.Context) { + if err := uuo.Exec(ctx); err != nil { + panic(err) + } +} + +func (uuo *UserUpdateOne) sqlSave(ctx context.Context) (_node *User, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: user.Table, + Columns: user.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + id, ok := uuo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "User.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := uuo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, user.FieldID) + for _, f := range fields { + if !user.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != user.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := uuo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := uuo.mutation.Name(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: user.FieldName, + }) + } + if uuo.mutation.LikedTweetsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.LikedTweetsTable, + Columns: user.LikedTweetsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: tweet.FieldID, + }, + }, + } + createE := &TweetLikeCreate{config: uuo.config, mutation: newTweetLikeMutation(uuo.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uuo.mutation.RemovedLikedTweetsIDs(); len(nodes) > 0 && !uuo.mutation.LikedTweetsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.LikedTweetsTable, + Columns: user.LikedTweetsPrimaryKey, + 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 := &TweetLikeCreate{config: uuo.config, mutation: newTweetLikeMutation(uuo.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uuo.mutation.LikedTweetsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.LikedTweetsTable, + Columns: user.LikedTweetsPrimaryKey, + 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 := &TweetLikeCreate{config: uuo.config, mutation: newTweetLikeMutation(uuo.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if uuo.mutation.GroupsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.GroupsTable, + Columns: user.GroupsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: group.FieldID, + }, + }, + } + createE := &UserGroupCreate{config: uuo.config, mutation: newUserGroupMutation(uuo.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uuo.mutation.RemovedGroupsIDs(); len(nodes) > 0 && !uuo.mutation.GroupsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.GroupsTable, + Columns: user.GroupsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: group.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + createE := &UserGroupCreate{config: uuo.config, mutation: newUserGroupMutation(uuo.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uuo.mutation.GroupsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.GroupsTable, + Columns: user.GroupsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: group.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + createE := &UserGroupCreate{config: uuo.config, mutation: newUserGroupMutation(uuo.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if uuo.mutation.FriendsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.FriendsTable, + Columns: user.FriendsPrimaryKey, + Bidi: true, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + createE := &FriendshipCreate{config: uuo.config, mutation: newFriendshipMutation(uuo.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uuo.mutation.RemovedFriendsIDs(); len(nodes) > 0 && !uuo.mutation.FriendsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.FriendsTable, + Columns: user.FriendsPrimaryKey, + Bidi: true, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + createE := &FriendshipCreate{config: uuo.config, mutation: newFriendshipMutation(uuo.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uuo.mutation.FriendsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.FriendsTable, + Columns: user.FriendsPrimaryKey, + Bidi: true, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + createE := &FriendshipCreate{config: uuo.config, mutation: newFriendshipMutation(uuo.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if uuo.mutation.RelativesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.RelativesTable, + Columns: user.RelativesPrimaryKey, + Bidi: true, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + createE := &RelationshipCreate{config: uuo.config, mutation: newRelationshipMutation(uuo.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uuo.mutation.RemovedRelativesIDs(); len(nodes) > 0 && !uuo.mutation.RelativesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.RelativesTable, + Columns: user.RelativesPrimaryKey, + Bidi: true, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + createE := &RelationshipCreate{config: uuo.config, mutation: newRelationshipMutation(uuo.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uuo.mutation.RelativesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.RelativesTable, + Columns: user.RelativesPrimaryKey, + Bidi: true, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + createE := &RelationshipCreate{config: uuo.config, mutation: newRelationshipMutation(uuo.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if uuo.mutation.JoinedGroupsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: user.JoinedGroupsTable, + Columns: []string{user.JoinedGroupsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: usergroup.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uuo.mutation.RemovedJoinedGroupsIDs(); len(nodes) > 0 && !uuo.mutation.JoinedGroupsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: user.JoinedGroupsTable, + Columns: []string{user.JoinedGroupsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: usergroup.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uuo.mutation.JoinedGroupsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: user.JoinedGroupsTable, + Columns: []string{user.JoinedGroupsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: usergroup.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if uuo.mutation.FriendshipsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: user.FriendshipsTable, + Columns: []string{user.FriendshipsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: friendship.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uuo.mutation.RemovedFriendshipsIDs(); len(nodes) > 0 && !uuo.mutation.FriendshipsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: user.FriendshipsTable, + Columns: []string{user.FriendshipsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: friendship.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uuo.mutation.FriendshipsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: user.FriendshipsTable, + Columns: []string{user.FriendshipsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: friendship.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &User{config: uuo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, uuo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{user.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return nil, err + } + return _node, nil +} diff --git a/entc/integration/edgeschema/ent/usergroup.go b/entc/integration/edgeschema/ent/usergroup.go new file mode 100644 index 0000000000..e03472565c --- /dev/null +++ b/entc/integration/edgeschema/ent/usergroup.go @@ -0,0 +1,176 @@ +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "fmt" + "strings" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/entc/integration/edgeschema/ent/group" + "entgo.io/ent/entc/integration/edgeschema/ent/user" + "entgo.io/ent/entc/integration/edgeschema/ent/usergroup" +) + +// UserGroup is the model entity for the UserGroup schema. +type UserGroup struct { + config `json:"-"` + // ID of the ent. + ID int `json:"id,omitempty"` + // JoinedAt holds the value of the "joined_at" field. + JoinedAt time.Time `json:"joined_at,omitempty"` + // UserID holds the value of the "user_id" field. + UserID int `json:"user_id,omitempty"` + // GroupID holds the value of the "group_id" field. + GroupID int `json:"group_id,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the UserGroupQuery when eager-loading is set. + Edges UserGroupEdges `json:"edges"` +} + +// UserGroupEdges holds the relations/edges for other nodes in the graph. +type UserGroupEdges struct { + // User holds the value of the user edge. + User *User `json:"user,omitempty"` + // Group holds the value of the group edge. + Group *Group `json:"group,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [2]bool +} + +// UserOrErr returns the User value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e UserGroupEdges) UserOrErr() (*User, error) { + if e.loadedTypes[0] { + if e.User == nil { + // The edge user was loaded in eager-loading, + // but was not found. + return nil, &NotFoundError{label: user.Label} + } + return e.User, nil + } + return nil, &NotLoadedError{edge: "user"} +} + +// GroupOrErr returns the Group value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e UserGroupEdges) GroupOrErr() (*Group, error) { + if e.loadedTypes[1] { + if e.Group == nil { + // The edge group was loaded in eager-loading, + // but was not found. + return nil, &NotFoundError{label: group.Label} + } + return e.Group, nil + } + return nil, &NotLoadedError{edge: "group"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*UserGroup) scanValues(columns []string) ([]interface{}, error) { + values := make([]interface{}, len(columns)) + for i := range columns { + switch columns[i] { + case usergroup.FieldID, usergroup.FieldUserID, usergroup.FieldGroupID: + values[i] = new(sql.NullInt64) + case usergroup.FieldJoinedAt: + values[i] = new(sql.NullTime) + default: + return nil, fmt.Errorf("unexpected column %q for type UserGroup", columns[i]) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the UserGroup fields. +func (ug *UserGroup) 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 usergroup.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + ug.ID = int(value.Int64) + case usergroup.FieldJoinedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field joined_at", values[i]) + } else if value.Valid { + ug.JoinedAt = value.Time + } + case usergroup.FieldUserID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field user_id", values[i]) + } else if value.Valid { + ug.UserID = int(value.Int64) + } + case usergroup.FieldGroupID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field group_id", values[i]) + } else if value.Valid { + ug.GroupID = int(value.Int64) + } + } + } + return nil +} + +// QueryUser queries the "user" edge of the UserGroup entity. +func (ug *UserGroup) QueryUser() *UserQuery { + return (&UserGroupClient{config: ug.config}).QueryUser(ug) +} + +// QueryGroup queries the "group" edge of the UserGroup entity. +func (ug *UserGroup) QueryGroup() *GroupQuery { + return (&UserGroupClient{config: ug.config}).QueryGroup(ug) +} + +// Update returns a builder for updating this UserGroup. +// Note that you need to call UserGroup.Unwrap() before calling this method if this UserGroup +// was returned from a transaction, and the transaction was committed or rolled back. +func (ug *UserGroup) Update() *UserGroupUpdateOne { + return (&UserGroupClient{config: ug.config}).UpdateOne(ug) +} + +// Unwrap unwraps the UserGroup 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 (ug *UserGroup) Unwrap() *UserGroup { + tx, ok := ug.config.driver.(*txDriver) + if !ok { + panic("ent: UserGroup is not a transactional entity") + } + ug.config.driver = tx.drv + return ug +} + +// String implements the fmt.Stringer. +func (ug *UserGroup) String() string { + var builder strings.Builder + builder.WriteString("UserGroup(") + builder.WriteString(fmt.Sprintf("id=%v, ", ug.ID)) + builder.WriteString("joined_at=") + builder.WriteString(ug.JoinedAt.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("user_id=") + builder.WriteString(fmt.Sprintf("%v", ug.UserID)) + builder.WriteString(", ") + builder.WriteString("group_id=") + builder.WriteString(fmt.Sprintf("%v", ug.GroupID)) + builder.WriteByte(')') + return builder.String() +} + +// UserGroups is a parsable slice of UserGroup. +type UserGroups []*UserGroup + +func (ug UserGroups) config(cfg config) { + for _i := range ug { + ug[_i].config = cfg + } +} diff --git a/entc/integration/edgeschema/ent/usergroup/usergroup.go b/entc/integration/edgeschema/ent/usergroup/usergroup.go new file mode 100644 index 0000000000..aa2751aa56 --- /dev/null +++ b/entc/integration/edgeschema/ent/usergroup/usergroup.go @@ -0,0 +1,63 @@ +// Code generated by entc, DO NOT EDIT. + +package usergroup + +import ( + "time" +) + +const ( + // Label holds the string label denoting the usergroup type in the database. + Label = "user_group" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldJoinedAt holds the string denoting the joined_at field in the database. + FieldJoinedAt = "joined_at" + // FieldUserID holds the string denoting the user_id field in the database. + FieldUserID = "user_id" + // FieldGroupID holds the string denoting the group_id field in the database. + FieldGroupID = "group_id" + // EdgeUser holds the string denoting the user edge name in mutations. + EdgeUser = "user" + // EdgeGroup holds the string denoting the group edge name in mutations. + EdgeGroup = "group" + // Table holds the table name of the usergroup in the database. + Table = "user_groups" + // UserTable is the table that holds the user relation/edge. + UserTable = "user_groups" + // 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" + // UserColumn is the table column denoting the user relation/edge. + UserColumn = "user_id" + // GroupTable is the table that holds the group relation/edge. + GroupTable = "user_groups" + // GroupInverseTable is the table name for the Group entity. + // It exists in this package in order to avoid circular dependency with the "group" package. + GroupInverseTable = "groups" + // GroupColumn is the table column denoting the group relation/edge. + GroupColumn = "group_id" +) + +// Columns holds all SQL columns for usergroup fields. +var Columns = []string{ + FieldID, + FieldJoinedAt, + FieldUserID, + FieldGroupID, +} + +// 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 ( + // DefaultJoinedAt holds the default value on creation for the "joined_at" field. + DefaultJoinedAt func() time.Time +) diff --git a/entc/integration/edgeschema/ent/usergroup/where.go b/entc/integration/edgeschema/ent/usergroup/where.go new file mode 100644 index 0000000000..ef7a98a687 --- /dev/null +++ b/entc/integration/edgeschema/ent/usergroup/where.go @@ -0,0 +1,375 @@ +// Code generated by entc, DO NOT EDIT. + +package usergroup + +import ( + "time" + + "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.UserGroup { + return predicate.UserGroup(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.UserGroup { + return predicate.UserGroup(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.UserGroup { + return predicate.UserGroup(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.UserGroup { + return predicate.UserGroup(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.UserGroup { + return predicate.UserGroup(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.UserGroup { + return predicate.UserGroup(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.UserGroup { + return predicate.UserGroup(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.UserGroup { + return predicate.UserGroup(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.UserGroup { + return predicate.UserGroup(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldID), id)) + }) +} + +// JoinedAt applies equality check predicate on the "joined_at" field. It's identical to JoinedAtEQ. +func JoinedAt(v time.Time) predicate.UserGroup { + return predicate.UserGroup(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldJoinedAt), v)) + }) +} + +// UserID applies equality check predicate on the "user_id" field. It's identical to UserIDEQ. +func UserID(v int) predicate.UserGroup { + return predicate.UserGroup(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldUserID), v)) + }) +} + +// GroupID applies equality check predicate on the "group_id" field. It's identical to GroupIDEQ. +func GroupID(v int) predicate.UserGroup { + return predicate.UserGroup(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldGroupID), v)) + }) +} + +// JoinedAtEQ applies the EQ predicate on the "joined_at" field. +func JoinedAtEQ(v time.Time) predicate.UserGroup { + return predicate.UserGroup(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldJoinedAt), v)) + }) +} + +// JoinedAtNEQ applies the NEQ predicate on the "joined_at" field. +func JoinedAtNEQ(v time.Time) predicate.UserGroup { + return predicate.UserGroup(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldJoinedAt), v)) + }) +} + +// JoinedAtIn applies the In predicate on the "joined_at" field. +func JoinedAtIn(vs ...time.Time) predicate.UserGroup { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.UserGroup(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(FieldJoinedAt), v...)) + }) +} + +// JoinedAtNotIn applies the NotIn predicate on the "joined_at" field. +func JoinedAtNotIn(vs ...time.Time) predicate.UserGroup { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.UserGroup(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(FieldJoinedAt), v...)) + }) +} + +// JoinedAtGT applies the GT predicate on the "joined_at" field. +func JoinedAtGT(v time.Time) predicate.UserGroup { + return predicate.UserGroup(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldJoinedAt), v)) + }) +} + +// JoinedAtGTE applies the GTE predicate on the "joined_at" field. +func JoinedAtGTE(v time.Time) predicate.UserGroup { + return predicate.UserGroup(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldJoinedAt), v)) + }) +} + +// JoinedAtLT applies the LT predicate on the "joined_at" field. +func JoinedAtLT(v time.Time) predicate.UserGroup { + return predicate.UserGroup(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldJoinedAt), v)) + }) +} + +// JoinedAtLTE applies the LTE predicate on the "joined_at" field. +func JoinedAtLTE(v time.Time) predicate.UserGroup { + return predicate.UserGroup(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldJoinedAt), v)) + }) +} + +// UserIDEQ applies the EQ predicate on the "user_id" field. +func UserIDEQ(v int) predicate.UserGroup { + return predicate.UserGroup(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldUserID), v)) + }) +} + +// UserIDNEQ applies the NEQ predicate on the "user_id" field. +func UserIDNEQ(v int) predicate.UserGroup { + return predicate.UserGroup(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldUserID), v)) + }) +} + +// UserIDIn applies the In predicate on the "user_id" field. +func UserIDIn(vs ...int) predicate.UserGroup { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.UserGroup(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(FieldUserID), v...)) + }) +} + +// UserIDNotIn applies the NotIn predicate on the "user_id" field. +func UserIDNotIn(vs ...int) predicate.UserGroup { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.UserGroup(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(FieldUserID), v...)) + }) +} + +// GroupIDEQ applies the EQ predicate on the "group_id" field. +func GroupIDEQ(v int) predicate.UserGroup { + return predicate.UserGroup(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldGroupID), v)) + }) +} + +// GroupIDNEQ applies the NEQ predicate on the "group_id" field. +func GroupIDNEQ(v int) predicate.UserGroup { + return predicate.UserGroup(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldGroupID), v)) + }) +} + +// GroupIDIn applies the In predicate on the "group_id" field. +func GroupIDIn(vs ...int) predicate.UserGroup { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.UserGroup(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(FieldGroupID), v...)) + }) +} + +// GroupIDNotIn applies the NotIn predicate on the "group_id" field. +func GroupIDNotIn(vs ...int) predicate.UserGroup { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.UserGroup(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(FieldGroupID), v...)) + }) +} + +// HasUser applies the HasEdge predicate on the "user" edge. +func HasUser() predicate.UserGroup { + return predicate.UserGroup(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(UserTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, UserTable, UserColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasUserWith applies the HasEdge predicate on the "user" edge with a given conditions (other predicates). +func HasUserWith(preds ...predicate.User) predicate.UserGroup { + return predicate.UserGroup(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(UserInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, UserTable, UserColumn), + ) + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasGroup applies the HasEdge predicate on the "group" edge. +func HasGroup() predicate.UserGroup { + return predicate.UserGroup(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(GroupTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, GroupTable, GroupColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasGroupWith applies the HasEdge predicate on the "group" edge with a given conditions (other predicates). +func HasGroupWith(preds ...predicate.Group) predicate.UserGroup { + return predicate.UserGroup(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(GroupInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, GroupTable, GroupColumn), + ) + 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.UserGroup) predicate.UserGroup { + return predicate.UserGroup(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.UserGroup) predicate.UserGroup { + return predicate.UserGroup(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.UserGroup) predicate.UserGroup { + return predicate.UserGroup(func(s *sql.Selector) { + p(s.Not()) + }) +} diff --git a/entc/integration/edgeschema/ent/usergroup_create.go b/entc/integration/edgeschema/ent/usergroup_create.go new file mode 100644 index 0000000000..b6d7edb8e6 --- /dev/null +++ b/entc/integration/edgeschema/ent/usergroup_create.go @@ -0,0 +1,321 @@ +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/edgeschema/ent/group" + "entgo.io/ent/entc/integration/edgeschema/ent/user" + "entgo.io/ent/entc/integration/edgeschema/ent/usergroup" + "entgo.io/ent/schema/field" +) + +// UserGroupCreate is the builder for creating a UserGroup entity. +type UserGroupCreate struct { + config + mutation *UserGroupMutation + hooks []Hook +} + +// SetJoinedAt sets the "joined_at" field. +func (ugc *UserGroupCreate) SetJoinedAt(t time.Time) *UserGroupCreate { + ugc.mutation.SetJoinedAt(t) + return ugc +} + +// SetNillableJoinedAt sets the "joined_at" field if the given value is not nil. +func (ugc *UserGroupCreate) SetNillableJoinedAt(t *time.Time) *UserGroupCreate { + if t != nil { + ugc.SetJoinedAt(*t) + } + return ugc +} + +// SetUserID sets the "user_id" field. +func (ugc *UserGroupCreate) SetUserID(i int) *UserGroupCreate { + ugc.mutation.SetUserID(i) + return ugc +} + +// SetGroupID sets the "group_id" field. +func (ugc *UserGroupCreate) SetGroupID(i int) *UserGroupCreate { + ugc.mutation.SetGroupID(i) + return ugc +} + +// SetUser sets the "user" edge to the User entity. +func (ugc *UserGroupCreate) SetUser(u *User) *UserGroupCreate { + return ugc.SetUserID(u.ID) +} + +// SetGroup sets the "group" edge to the Group entity. +func (ugc *UserGroupCreate) SetGroup(g *Group) *UserGroupCreate { + return ugc.SetGroupID(g.ID) +} + +// Mutation returns the UserGroupMutation object of the builder. +func (ugc *UserGroupCreate) Mutation() *UserGroupMutation { + return ugc.mutation +} + +// Save creates the UserGroup in the database. +func (ugc *UserGroupCreate) Save(ctx context.Context) (*UserGroup, error) { + var ( + err error + node *UserGroup + ) + ugc.defaults() + if len(ugc.hooks) == 0 { + if err = ugc.check(); err != nil { + return nil, err + } + node, err = ugc.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*UserGroupMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err = ugc.check(); err != nil { + return nil, err + } + ugc.mutation = mutation + if node, err = ugc.sqlSave(ctx); err != nil { + return nil, err + } + mutation.id = &node.ID + mutation.done = true + return node, err + }) + for i := len(ugc.hooks) - 1; i >= 0; i-- { + if ugc.hooks[i] == nil { + return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = ugc.hooks[i](mut) + } + v, err := mut.Mutate(ctx, ugc.mutation) + if err != nil { + return nil, err + } + nv, ok := v.(*UserGroup) + if !ok { + return nil, fmt.Errorf("unexpected node type %T returned from UserGroupMutation", v) + } + node = nv + } + return node, err +} + +// SaveX calls Save and panics if Save returns an error. +func (ugc *UserGroupCreate) SaveX(ctx context.Context) *UserGroup { + v, err := ugc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (ugc *UserGroupCreate) Exec(ctx context.Context) error { + _, err := ugc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (ugc *UserGroupCreate) ExecX(ctx context.Context) { + if err := ugc.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (ugc *UserGroupCreate) defaults() { + if _, ok := ugc.mutation.JoinedAt(); !ok { + v := usergroup.DefaultJoinedAt() + ugc.mutation.SetJoinedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (ugc *UserGroupCreate) check() error { + if _, ok := ugc.mutation.JoinedAt(); !ok { + return &ValidationError{Name: "joined_at", err: errors.New(`ent: missing required field "UserGroup.joined_at"`)} + } + if _, ok := ugc.mutation.UserID(); !ok { + return &ValidationError{Name: "user_id", err: errors.New(`ent: missing required field "UserGroup.user_id"`)} + } + if _, ok := ugc.mutation.GroupID(); !ok { + return &ValidationError{Name: "group_id", err: errors.New(`ent: missing required field "UserGroup.group_id"`)} + } + if _, ok := ugc.mutation.UserID(); !ok { + return &ValidationError{Name: "user", err: errors.New(`ent: missing required edge "UserGroup.user"`)} + } + if _, ok := ugc.mutation.GroupID(); !ok { + return &ValidationError{Name: "group", err: errors.New(`ent: missing required edge "UserGroup.group"`)} + } + return nil +} + +func (ugc *UserGroupCreate) sqlSave(ctx context.Context) (*UserGroup, error) { + _node, _spec := ugc.createSpec() + if err := sqlgraph.CreateNode(ctx, ugc.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return nil, err + } + id := _spec.ID.Value.(int64) + _node.ID = int(id) + return _node, nil +} + +func (ugc *UserGroupCreate) createSpec() (*UserGroup, *sqlgraph.CreateSpec) { + var ( + _node = &UserGroup{config: ugc.config} + _spec = &sqlgraph.CreateSpec{ + Table: usergroup.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: usergroup.FieldID, + }, + } + ) + if value, ok := ugc.mutation.JoinedAt(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: usergroup.FieldJoinedAt, + }) + _node.JoinedAt = value + } + if nodes := ugc.mutation.UserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: usergroup.UserTable, + Columns: []string{usergroup.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.UserID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := ugc.mutation.GroupIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: usergroup.GroupTable, + Columns: []string{usergroup.GroupColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: group.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.GroupID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// UserGroupCreateBulk is the builder for creating many UserGroup entities in bulk. +type UserGroupCreateBulk struct { + config + builders []*UserGroupCreate +} + +// Save creates the UserGroup entities in the database. +func (ugcb *UserGroupCreateBulk) Save(ctx context.Context) ([]*UserGroup, error) { + specs := make([]*sqlgraph.CreateSpec, len(ugcb.builders)) + nodes := make([]*UserGroup, len(ugcb.builders)) + mutators := make([]Mutator, len(ugcb.builders)) + for i := range ugcb.builders { + func(i int, root context.Context) { + builder := ugcb.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*UserGroupMutation) + 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, ugcb.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, ugcb.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), 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, ugcb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (ugcb *UserGroupCreateBulk) SaveX(ctx context.Context) []*UserGroup { + v, err := ugcb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (ugcb *UserGroupCreateBulk) Exec(ctx context.Context) error { + _, err := ugcb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (ugcb *UserGroupCreateBulk) ExecX(ctx context.Context) { + if err := ugcb.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/entc/integration/edgeschema/ent/usergroup_delete.go b/entc/integration/edgeschema/ent/usergroup_delete.go new file mode 100644 index 0000000000..24ea9a724e --- /dev/null +++ b/entc/integration/edgeschema/ent/usergroup_delete.go @@ -0,0 +1,111 @@ +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "fmt" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/edgeschema/ent/predicate" + "entgo.io/ent/entc/integration/edgeschema/ent/usergroup" + "entgo.io/ent/schema/field" +) + +// UserGroupDelete is the builder for deleting a UserGroup entity. +type UserGroupDelete struct { + config + hooks []Hook + mutation *UserGroupMutation +} + +// Where appends a list predicates to the UserGroupDelete builder. +func (ugd *UserGroupDelete) Where(ps ...predicate.UserGroup) *UserGroupDelete { + ugd.mutation.Where(ps...) + return ugd +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (ugd *UserGroupDelete) Exec(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(ugd.hooks) == 0 { + affected, err = ugd.sqlExec(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*UserGroupMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + ugd.mutation = mutation + affected, err = ugd.sqlExec(ctx) + mutation.done = true + return affected, err + }) + for i := len(ugd.hooks) - 1; i >= 0; i-- { + if ugd.hooks[i] == nil { + return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = ugd.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, ugd.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// ExecX is like Exec, but panics if an error occurs. +func (ugd *UserGroupDelete) ExecX(ctx context.Context) int { + n, err := ugd.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (ugd *UserGroupDelete) sqlExec(ctx context.Context) (int, error) { + _spec := &sqlgraph.DeleteSpec{ + Node: &sqlgraph.NodeSpec{ + Table: usergroup.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: usergroup.FieldID, + }, + }, + } + if ps := ugd.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return sqlgraph.DeleteNodes(ctx, ugd.driver, _spec) +} + +// UserGroupDeleteOne is the builder for deleting a single UserGroup entity. +type UserGroupDeleteOne struct { + ugd *UserGroupDelete +} + +// Exec executes the deletion query. +func (ugdo *UserGroupDeleteOne) Exec(ctx context.Context) error { + n, err := ugdo.ugd.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{usergroup.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (ugdo *UserGroupDeleteOne) ExecX(ctx context.Context) { + ugdo.ugd.ExecX(ctx) +} diff --git a/entc/integration/edgeschema/ent/usergroup_query.go b/entc/integration/edgeschema/ent/usergroup_query.go new file mode 100644 index 0000000000..a418e24c51 --- /dev/null +++ b/entc/integration/edgeschema/ent/usergroup_query.go @@ -0,0 +1,659 @@ +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "fmt" + "math" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/edgeschema/ent/group" + "entgo.io/ent/entc/integration/edgeschema/ent/predicate" + "entgo.io/ent/entc/integration/edgeschema/ent/user" + "entgo.io/ent/entc/integration/edgeschema/ent/usergroup" + "entgo.io/ent/schema/field" +) + +// UserGroupQuery is the builder for querying UserGroup entities. +type UserGroupQuery struct { + config + limit *int + offset *int + unique *bool + order []OrderFunc + fields []string + predicates []predicate.UserGroup + // eager-loading edges. + withUser *UserQuery + withGroup *GroupQuery + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the UserGroupQuery builder. +func (ugq *UserGroupQuery) Where(ps ...predicate.UserGroup) *UserGroupQuery { + ugq.predicates = append(ugq.predicates, ps...) + return ugq +} + +// Limit adds a limit step to the query. +func (ugq *UserGroupQuery) Limit(limit int) *UserGroupQuery { + ugq.limit = &limit + return ugq +} + +// Offset adds an offset step to the query. +func (ugq *UserGroupQuery) Offset(offset int) *UserGroupQuery { + ugq.offset = &offset + return ugq +} + +// 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 (ugq *UserGroupQuery) Unique(unique bool) *UserGroupQuery { + ugq.unique = &unique + return ugq +} + +// Order adds an order step to the query. +func (ugq *UserGroupQuery) Order(o ...OrderFunc) *UserGroupQuery { + ugq.order = append(ugq.order, o...) + return ugq +} + +// QueryUser chains the current query on the "user" edge. +func (ugq *UserGroupQuery) QueryUser() *UserQuery { + query := &UserQuery{config: ugq.config} + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := ugq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := ugq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(usergroup.Table, usergroup.FieldID, selector), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, usergroup.UserTable, usergroup.UserColumn), + ) + fromU = sqlgraph.SetNeighbors(ugq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryGroup chains the current query on the "group" edge. +func (ugq *UserGroupQuery) QueryGroup() *GroupQuery { + query := &GroupQuery{config: ugq.config} + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := ugq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := ugq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(usergroup.Table, usergroup.FieldID, selector), + sqlgraph.To(group.Table, group.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, usergroup.GroupTable, usergroup.GroupColumn), + ) + fromU = sqlgraph.SetNeighbors(ugq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first UserGroup entity from the query. +// Returns a *NotFoundError when no UserGroup was found. +func (ugq *UserGroupQuery) First(ctx context.Context) (*UserGroup, error) { + nodes, err := ugq.Limit(1).All(ctx) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{usergroup.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (ugq *UserGroupQuery) FirstX(ctx context.Context) *UserGroup { + node, err := ugq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first UserGroup ID from the query. +// Returns a *NotFoundError when no UserGroup ID was found. +func (ugq *UserGroupQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = ugq.Limit(1).IDs(ctx); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{usergroup.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (ugq *UserGroupQuery) FirstIDX(ctx context.Context) int { + id, err := ugq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single UserGroup entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one UserGroup entity is found. +// Returns a *NotFoundError when no UserGroup entities are found. +func (ugq *UserGroupQuery) Only(ctx context.Context) (*UserGroup, error) { + nodes, err := ugq.Limit(2).All(ctx) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{usergroup.Label} + default: + return nil, &NotSingularError{usergroup.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (ugq *UserGroupQuery) OnlyX(ctx context.Context) *UserGroup { + node, err := ugq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only UserGroup ID in the query. +// Returns a *NotSingularError when more than one UserGroup ID is found. +// Returns a *NotFoundError when no entities are found. +func (ugq *UserGroupQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = ugq.Limit(2).IDs(ctx); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{usergroup.Label} + default: + err = &NotSingularError{usergroup.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (ugq *UserGroupQuery) OnlyIDX(ctx context.Context) int { + id, err := ugq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of UserGroups. +func (ugq *UserGroupQuery) All(ctx context.Context) ([]*UserGroup, error) { + if err := ugq.prepareQuery(ctx); err != nil { + return nil, err + } + return ugq.sqlAll(ctx) +} + +// AllX is like All, but panics if an error occurs. +func (ugq *UserGroupQuery) AllX(ctx context.Context) []*UserGroup { + nodes, err := ugq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of UserGroup IDs. +func (ugq *UserGroupQuery) IDs(ctx context.Context) ([]int, error) { + var ids []int + if err := ugq.Select(usergroup.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (ugq *UserGroupQuery) IDsX(ctx context.Context) []int { + ids, err := ugq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (ugq *UserGroupQuery) Count(ctx context.Context) (int, error) { + if err := ugq.prepareQuery(ctx); err != nil { + return 0, err + } + return ugq.sqlCount(ctx) +} + +// CountX is like Count, but panics if an error occurs. +func (ugq *UserGroupQuery) CountX(ctx context.Context) int { + count, err := ugq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (ugq *UserGroupQuery) Exist(ctx context.Context) (bool, error) { + if err := ugq.prepareQuery(ctx); err != nil { + return false, err + } + return ugq.sqlExist(ctx) +} + +// ExistX is like Exist, but panics if an error occurs. +func (ugq *UserGroupQuery) ExistX(ctx context.Context) bool { + exist, err := ugq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the UserGroupQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (ugq *UserGroupQuery) Clone() *UserGroupQuery { + if ugq == nil { + return nil + } + return &UserGroupQuery{ + config: ugq.config, + limit: ugq.limit, + offset: ugq.offset, + order: append([]OrderFunc{}, ugq.order...), + predicates: append([]predicate.UserGroup{}, ugq.predicates...), + withUser: ugq.withUser.Clone(), + withGroup: ugq.withGroup.Clone(), + // clone intermediate query. + sql: ugq.sql.Clone(), + path: ugq.path, + unique: ugq.unique, + } +} + +// WithUser tells the query-builder to eager-load the nodes that are connected to +// the "user" edge. The optional arguments are used to configure the query builder of the edge. +func (ugq *UserGroupQuery) WithUser(opts ...func(*UserQuery)) *UserGroupQuery { + query := &UserQuery{config: ugq.config} + for _, opt := range opts { + opt(query) + } + ugq.withUser = query + return ugq +} + +// WithGroup tells the query-builder to eager-load the nodes that are connected to +// the "group" edge. The optional arguments are used to configure the query builder of the edge. +func (ugq *UserGroupQuery) WithGroup(opts ...func(*GroupQuery)) *UserGroupQuery { + query := &GroupQuery{config: ugq.config} + for _, opt := range opts { + opt(query) + } + ugq.withGroup = query + return ugq +} + +// 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 { +// JoinedAt time.Time `json:"joined_at,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.UserGroup.Query(). +// GroupBy(usergroup.FieldJoinedAt). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +// +func (ugq *UserGroupQuery) GroupBy(field string, fields ...string) *UserGroupGroupBy { + grbuild := &UserGroupGroupBy{config: ugq.config} + grbuild.fields = append([]string{field}, fields...) + grbuild.path = func(ctx context.Context) (prev *sql.Selector, err error) { + if err := ugq.prepareQuery(ctx); err != nil { + return nil, err + } + return ugq.sqlQuery(ctx), nil + } + grbuild.label = usergroup.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 { +// JoinedAt time.Time `json:"joined_at,omitempty"` +// } +// +// client.UserGroup.Query(). +// Select(usergroup.FieldJoinedAt). +// Scan(ctx, &v) +// +func (ugq *UserGroupQuery) Select(fields ...string) *UserGroupSelect { + ugq.fields = append(ugq.fields, fields...) + selbuild := &UserGroupSelect{UserGroupQuery: ugq} + selbuild.label = usergroup.Label + selbuild.flds, selbuild.scan = &ugq.fields, selbuild.Scan + return selbuild +} + +func (ugq *UserGroupQuery) prepareQuery(ctx context.Context) error { + for _, f := range ugq.fields { + if !usergroup.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if ugq.path != nil { + prev, err := ugq.path(ctx) + if err != nil { + return err + } + ugq.sql = prev + } + return nil +} + +func (ugq *UserGroupQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*UserGroup, error) { + var ( + nodes = []*UserGroup{} + _spec = ugq.querySpec() + loadedTypes = [2]bool{ + ugq.withUser != nil, + ugq.withGroup != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]interface{}, error) { + return (*UserGroup).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []interface{}) error { + node := &UserGroup{config: ugq.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, ugq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + + if query := ugq.withUser; query != nil { + ids := make([]int, 0, len(nodes)) + nodeids := make(map[int][]*UserGroup) + for i := range nodes { + fk := nodes[i].UserID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + query.Where(user.IDIn(ids...)) + neighbors, err := query.All(ctx) + if err != nil { + return nil, err + } + for _, n := range neighbors { + nodes, ok := nodeids[n.ID] + if !ok { + return nil, fmt.Errorf(`unexpected foreign-key "user_id" returned %v`, n.ID) + } + for i := range nodes { + nodes[i].Edges.User = n + } + } + } + + if query := ugq.withGroup; query != nil { + ids := make([]int, 0, len(nodes)) + nodeids := make(map[int][]*UserGroup) + for i := range nodes { + fk := nodes[i].GroupID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + query.Where(group.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 "group_id" returned %v`, n.ID) + } + for i := range nodes { + nodes[i].Edges.Group = n + } + } + } + + return nodes, nil +} + +func (ugq *UserGroupQuery) sqlCount(ctx context.Context) (int, error) { + _spec := ugq.querySpec() + _spec.Node.Columns = ugq.fields + if len(ugq.fields) > 0 { + _spec.Unique = ugq.unique != nil && *ugq.unique + } + return sqlgraph.CountNodes(ctx, ugq.driver, _spec) +} + +func (ugq *UserGroupQuery) sqlExist(ctx context.Context) (bool, error) { + n, err := ugq.sqlCount(ctx) + if err != nil { + return false, fmt.Errorf("ent: check existence: %w", err) + } + return n > 0, nil +} + +func (ugq *UserGroupQuery) querySpec() *sqlgraph.QuerySpec { + _spec := &sqlgraph.QuerySpec{ + Node: &sqlgraph.NodeSpec{ + Table: usergroup.Table, + Columns: usergroup.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: usergroup.FieldID, + }, + }, + From: ugq.sql, + Unique: true, + } + if unique := ugq.unique; unique != nil { + _spec.Unique = *unique + } + if fields := ugq.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, usergroup.FieldID) + for i := range fields { + if fields[i] != usergroup.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := ugq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := ugq.limit; limit != nil { + _spec.Limit = *limit + } + if offset := ugq.offset; offset != nil { + _spec.Offset = *offset + } + if ps := ugq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (ugq *UserGroupQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(ugq.driver.Dialect()) + t1 := builder.Table(usergroup.Table) + columns := ugq.fields + if len(columns) == 0 { + columns = usergroup.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if ugq.sql != nil { + selector = ugq.sql + selector.Select(selector.Columns(columns...)...) + } + if ugq.unique != nil && *ugq.unique { + selector.Distinct() + } + for _, p := range ugq.predicates { + p(selector) + } + for _, p := range ugq.order { + p(selector) + } + if offset := ugq.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 := ugq.limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// UserGroupGroupBy is the group-by builder for UserGroup entities. +type UserGroupGroupBy 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 (uggb *UserGroupGroupBy) Aggregate(fns ...AggregateFunc) *UserGroupGroupBy { + uggb.fns = append(uggb.fns, fns...) + return uggb +} + +// Scan applies the group-by query and scans the result into the given value. +func (uggb *UserGroupGroupBy) Scan(ctx context.Context, v interface{}) error { + query, err := uggb.path(ctx) + if err != nil { + return err + } + uggb.sql = query + return uggb.sqlScan(ctx, v) +} + +func (uggb *UserGroupGroupBy) sqlScan(ctx context.Context, v interface{}) error { + for _, f := range uggb.fields { + if !usergroup.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)} + } + } + selector := uggb.sqlQuery() + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := uggb.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +func (uggb *UserGroupGroupBy) sqlQuery() *sql.Selector { + selector := uggb.sql.Select() + aggregation := make([]string, 0, len(uggb.fns)) + for _, fn := range uggb.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(uggb.fields)+len(uggb.fns)) + for _, f := range uggb.fields { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + return selector.GroupBy(selector.Columns(uggb.fields...)...) +} + +// UserGroupSelect is the builder for selecting fields of UserGroup entities. +type UserGroupSelect struct { + *UserGroupQuery + selector + // intermediate query (i.e. traversal path). + sql *sql.Selector +} + +// Scan applies the selector query and scans the result into the given value. +func (ugs *UserGroupSelect) Scan(ctx context.Context, v interface{}) error { + if err := ugs.prepareQuery(ctx); err != nil { + return err + } + ugs.sql = ugs.UserGroupQuery.sqlQuery(ctx) + return ugs.sqlScan(ctx, v) +} + +func (ugs *UserGroupSelect) sqlScan(ctx context.Context, v interface{}) error { + rows := &sql.Rows{} + query, args := ugs.sql.Query() + if err := ugs.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/usergroup_update.go b/entc/integration/edgeschema/ent/usergroup_update.go new file mode 100644 index 0000000000..1f5fc7ec04 --- /dev/null +++ b/entc/integration/edgeschema/ent/usergroup_update.go @@ -0,0 +1,532 @@ +// Code generated by entc, 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/group" + "entgo.io/ent/entc/integration/edgeschema/ent/predicate" + "entgo.io/ent/entc/integration/edgeschema/ent/user" + "entgo.io/ent/entc/integration/edgeschema/ent/usergroup" + "entgo.io/ent/schema/field" +) + +// UserGroupUpdate is the builder for updating UserGroup entities. +type UserGroupUpdate struct { + config + hooks []Hook + mutation *UserGroupMutation +} + +// Where appends a list predicates to the UserGroupUpdate builder. +func (ugu *UserGroupUpdate) Where(ps ...predicate.UserGroup) *UserGroupUpdate { + ugu.mutation.Where(ps...) + return ugu +} + +// SetJoinedAt sets the "joined_at" field. +func (ugu *UserGroupUpdate) SetJoinedAt(t time.Time) *UserGroupUpdate { + ugu.mutation.SetJoinedAt(t) + return ugu +} + +// SetNillableJoinedAt sets the "joined_at" field if the given value is not nil. +func (ugu *UserGroupUpdate) SetNillableJoinedAt(t *time.Time) *UserGroupUpdate { + if t != nil { + ugu.SetJoinedAt(*t) + } + return ugu +} + +// SetUserID sets the "user_id" field. +func (ugu *UserGroupUpdate) SetUserID(i int) *UserGroupUpdate { + ugu.mutation.SetUserID(i) + return ugu +} + +// SetGroupID sets the "group_id" field. +func (ugu *UserGroupUpdate) SetGroupID(i int) *UserGroupUpdate { + ugu.mutation.SetGroupID(i) + return ugu +} + +// SetUser sets the "user" edge to the User entity. +func (ugu *UserGroupUpdate) SetUser(u *User) *UserGroupUpdate { + return ugu.SetUserID(u.ID) +} + +// SetGroup sets the "group" edge to the Group entity. +func (ugu *UserGroupUpdate) SetGroup(g *Group) *UserGroupUpdate { + return ugu.SetGroupID(g.ID) +} + +// Mutation returns the UserGroupMutation object of the builder. +func (ugu *UserGroupUpdate) Mutation() *UserGroupMutation { + return ugu.mutation +} + +// ClearUser clears the "user" edge to the User entity. +func (ugu *UserGroupUpdate) ClearUser() *UserGroupUpdate { + ugu.mutation.ClearUser() + return ugu +} + +// ClearGroup clears the "group" edge to the Group entity. +func (ugu *UserGroupUpdate) ClearGroup() *UserGroupUpdate { + ugu.mutation.ClearGroup() + return ugu +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (ugu *UserGroupUpdate) Save(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(ugu.hooks) == 0 { + if err = ugu.check(); err != nil { + return 0, err + } + affected, err = ugu.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*UserGroupMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err = ugu.check(); err != nil { + return 0, err + } + ugu.mutation = mutation + affected, err = ugu.sqlSave(ctx) + mutation.done = true + return affected, err + }) + for i := len(ugu.hooks) - 1; i >= 0; i-- { + if ugu.hooks[i] == nil { + return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = ugu.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, ugu.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// SaveX is like Save, but panics if an error occurs. +func (ugu *UserGroupUpdate) SaveX(ctx context.Context) int { + affected, err := ugu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (ugu *UserGroupUpdate) Exec(ctx context.Context) error { + _, err := ugu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (ugu *UserGroupUpdate) ExecX(ctx context.Context) { + if err := ugu.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (ugu *UserGroupUpdate) check() error { + if _, ok := ugu.mutation.UserID(); ugu.mutation.UserCleared() && !ok { + return errors.New(`ent: clearing a required unique edge "UserGroup.user"`) + } + if _, ok := ugu.mutation.GroupID(); ugu.mutation.GroupCleared() && !ok { + return errors.New(`ent: clearing a required unique edge "UserGroup.group"`) + } + return nil +} + +func (ugu *UserGroupUpdate) sqlSave(ctx context.Context) (n int, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: usergroup.Table, + Columns: usergroup.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: usergroup.FieldID, + }, + }, + } + if ps := ugu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := ugu.mutation.JoinedAt(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: usergroup.FieldJoinedAt, + }) + } + if ugu.mutation.UserCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: usergroup.UserTable, + Columns: []string{usergroup.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := ugu.mutation.UserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: usergroup.UserTable, + Columns: []string{usergroup.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if ugu.mutation.GroupCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: usergroup.GroupTable, + Columns: []string{usergroup.GroupColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: group.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := ugu.mutation.GroupIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: usergroup.GroupTable, + Columns: []string{usergroup.GroupColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: group.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, ugu.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{usergroup.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return 0, err + } + return n, nil +} + +// UserGroupUpdateOne is the builder for updating a single UserGroup entity. +type UserGroupUpdateOne struct { + config + fields []string + hooks []Hook + mutation *UserGroupMutation +} + +// SetJoinedAt sets the "joined_at" field. +func (uguo *UserGroupUpdateOne) SetJoinedAt(t time.Time) *UserGroupUpdateOne { + uguo.mutation.SetJoinedAt(t) + return uguo +} + +// SetNillableJoinedAt sets the "joined_at" field if the given value is not nil. +func (uguo *UserGroupUpdateOne) SetNillableJoinedAt(t *time.Time) *UserGroupUpdateOne { + if t != nil { + uguo.SetJoinedAt(*t) + } + return uguo +} + +// SetUserID sets the "user_id" field. +func (uguo *UserGroupUpdateOne) SetUserID(i int) *UserGroupUpdateOne { + uguo.mutation.SetUserID(i) + return uguo +} + +// SetGroupID sets the "group_id" field. +func (uguo *UserGroupUpdateOne) SetGroupID(i int) *UserGroupUpdateOne { + uguo.mutation.SetGroupID(i) + return uguo +} + +// SetUser sets the "user" edge to the User entity. +func (uguo *UserGroupUpdateOne) SetUser(u *User) *UserGroupUpdateOne { + return uguo.SetUserID(u.ID) +} + +// SetGroup sets the "group" edge to the Group entity. +func (uguo *UserGroupUpdateOne) SetGroup(g *Group) *UserGroupUpdateOne { + return uguo.SetGroupID(g.ID) +} + +// Mutation returns the UserGroupMutation object of the builder. +func (uguo *UserGroupUpdateOne) Mutation() *UserGroupMutation { + return uguo.mutation +} + +// ClearUser clears the "user" edge to the User entity. +func (uguo *UserGroupUpdateOne) ClearUser() *UserGroupUpdateOne { + uguo.mutation.ClearUser() + return uguo +} + +// ClearGroup clears the "group" edge to the Group entity. +func (uguo *UserGroupUpdateOne) ClearGroup() *UserGroupUpdateOne { + uguo.mutation.ClearGroup() + return uguo +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (uguo *UserGroupUpdateOne) Select(field string, fields ...string) *UserGroupUpdateOne { + uguo.fields = append([]string{field}, fields...) + return uguo +} + +// Save executes the query and returns the updated UserGroup entity. +func (uguo *UserGroupUpdateOne) Save(ctx context.Context) (*UserGroup, error) { + var ( + err error + node *UserGroup + ) + if len(uguo.hooks) == 0 { + if err = uguo.check(); err != nil { + return nil, err + } + node, err = uguo.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*UserGroupMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err = uguo.check(); err != nil { + return nil, err + } + uguo.mutation = mutation + node, err = uguo.sqlSave(ctx) + mutation.done = true + return node, err + }) + for i := len(uguo.hooks) - 1; i >= 0; i-- { + if uguo.hooks[i] == nil { + return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = uguo.hooks[i](mut) + } + v, err := mut.Mutate(ctx, uguo.mutation) + if err != nil { + return nil, err + } + nv, ok := v.(*UserGroup) + if !ok { + return nil, fmt.Errorf("unexpected node type %T returned from UserGroupMutation", v) + } + node = nv + } + return node, err +} + +// SaveX is like Save, but panics if an error occurs. +func (uguo *UserGroupUpdateOne) SaveX(ctx context.Context) *UserGroup { + node, err := uguo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (uguo *UserGroupUpdateOne) Exec(ctx context.Context) error { + _, err := uguo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (uguo *UserGroupUpdateOne) ExecX(ctx context.Context) { + if err := uguo.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (uguo *UserGroupUpdateOne) check() error { + if _, ok := uguo.mutation.UserID(); uguo.mutation.UserCleared() && !ok { + return errors.New(`ent: clearing a required unique edge "UserGroup.user"`) + } + if _, ok := uguo.mutation.GroupID(); uguo.mutation.GroupCleared() && !ok { + return errors.New(`ent: clearing a required unique edge "UserGroup.group"`) + } + return nil +} + +func (uguo *UserGroupUpdateOne) sqlSave(ctx context.Context) (_node *UserGroup, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: usergroup.Table, + Columns: usergroup.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: usergroup.FieldID, + }, + }, + } + id, ok := uguo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "UserGroup.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := uguo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, usergroup.FieldID) + for _, f := range fields { + if !usergroup.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != usergroup.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := uguo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := uguo.mutation.JoinedAt(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: usergroup.FieldJoinedAt, + }) + } + if uguo.mutation.UserCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: usergroup.UserTable, + Columns: []string{usergroup.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uguo.mutation.UserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: usergroup.UserTable, + Columns: []string{usergroup.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if uguo.mutation.GroupCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: usergroup.GroupTable, + Columns: []string{usergroup.GroupColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: group.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uguo.mutation.GroupIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: usergroup.GroupTable, + Columns: []string{usergroup.GroupColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: group.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &UserGroup{config: uguo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, uguo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{usergroup.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return nil, err + } + return _node, nil +} diff --git a/entc/integration/ent/card.go b/entc/integration/ent/card.go index fb73c28ebd..7bea7fcf5c 100644 --- a/entc/integration/ent/card.go +++ b/entc/integration/ent/card.go @@ -185,16 +185,20 @@ func (c *Card) Unwrap() *Card { func (c *Card) String() string { var builder strings.Builder builder.WriteString("Card(") - builder.WriteString(fmt.Sprintf("id=%v", c.ID)) - builder.WriteString(", create_time=") + builder.WriteString(fmt.Sprintf("id=%v, ", c.ID)) + builder.WriteString("create_time=") builder.WriteString(c.CreateTime.Format(time.ANSIC)) - builder.WriteString(", update_time=") + builder.WriteString(", ") + builder.WriteString("update_time=") builder.WriteString(c.UpdateTime.Format(time.ANSIC)) - builder.WriteString(", balance=") + builder.WriteString(", ") + builder.WriteString("balance=") builder.WriteString(fmt.Sprintf("%v", c.Balance)) - builder.WriteString(", number=") + builder.WriteString(", ") + builder.WriteString("number=") builder.WriteString(c.Number) - builder.WriteString(", name=") + builder.WriteString(", ") + builder.WriteString("name=") builder.WriteString(c.Name) builder.WriteByte(')') return builder.String() diff --git a/entc/integration/ent/card_create.go b/entc/integration/ent/card_create.go index 21c8254e7a..50e3ee0ecd 100644 --- a/entc/integration/ent/card_create.go +++ b/entc/integration/ent/card_create.go @@ -682,11 +682,11 @@ func (ccb *CardCreateBulk) Save(ctx context.Context) ([]*Card, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/entc/integration/ent/client.go b/entc/integration/ent/client.go index 24a1ff3598..49b41a16d6 100644 --- a/entc/integration/ent/client.go +++ b/entc/integration/ent/client.go @@ -240,7 +240,7 @@ func (c *CardClient) Use(hooks ...Hook) { c.hooks.Card = append(c.hooks.Card, hooks...) } -// Create returns a create builder for Card. +// Create returns a builder for creating a Card entity. func (c *CardClient) Create() *CardCreate { mutation := newCardMutation(c.config, OpCreate) return &CardCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -275,12 +275,12 @@ func (c *CardClient) Delete() *CardDelete { return &CardDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *CardClient) DeleteOne(ca *Card) *CardDeleteOne { return c.DeleteOneID(ca.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *CardClient) DeleteOneID(id int) *CardDeleteOne { builder := c.Delete().Where(card.ID(id)) builder.mutation.id = &id @@ -362,7 +362,7 @@ func (c *CommentClient) Use(hooks ...Hook) { c.hooks.Comment = append(c.hooks.Comment, hooks...) } -// Create returns a create builder for Comment. +// Create returns a builder for creating a Comment entity. func (c *CommentClient) Create() *CommentCreate { mutation := newCommentMutation(c.config, OpCreate) return &CommentCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -397,12 +397,12 @@ func (c *CommentClient) Delete() *CommentDelete { return &CommentDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *CommentClient) DeleteOne(co *Comment) *CommentDeleteOne { return c.DeleteOneID(co.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *CommentClient) DeleteOneID(id int) *CommentDeleteOne { builder := c.Delete().Where(comment.ID(id)) builder.mutation.id = &id @@ -452,7 +452,7 @@ func (c *FieldTypeClient) Use(hooks ...Hook) { c.hooks.FieldType = append(c.hooks.FieldType, hooks...) } -// Create returns a create builder for FieldType. +// Create returns a builder for creating a FieldType entity. func (c *FieldTypeClient) Create() *FieldTypeCreate { mutation := newFieldTypeMutation(c.config, OpCreate) return &FieldTypeCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -487,12 +487,12 @@ func (c *FieldTypeClient) Delete() *FieldTypeDelete { return &FieldTypeDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *FieldTypeClient) DeleteOne(ft *FieldType) *FieldTypeDeleteOne { return c.DeleteOneID(ft.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *FieldTypeClient) DeleteOneID(id int) *FieldTypeDeleteOne { builder := c.Delete().Where(fieldtype.ID(id)) builder.mutation.id = &id @@ -542,7 +542,7 @@ func (c *FileClient) Use(hooks ...Hook) { c.hooks.File = append(c.hooks.File, hooks...) } -// Create returns a create builder for File. +// Create returns a builder for creating a File entity. func (c *FileClient) Create() *FileCreate { mutation := newFileMutation(c.config, OpCreate) return &FileCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -577,12 +577,12 @@ func (c *FileClient) Delete() *FileDelete { return &FileDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *FileClient) DeleteOne(f *File) *FileDeleteOne { return c.DeleteOneID(f.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *FileClient) DeleteOneID(id int) *FileDeleteOne { builder := c.Delete().Where(file.ID(id)) builder.mutation.id = &id @@ -680,7 +680,7 @@ func (c *FileTypeClient) Use(hooks ...Hook) { c.hooks.FileType = append(c.hooks.FileType, hooks...) } -// Create returns a create builder for FileType. +// Create returns a builder for creating a FileType entity. func (c *FileTypeClient) Create() *FileTypeCreate { mutation := newFileTypeMutation(c.config, OpCreate) return &FileTypeCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -715,12 +715,12 @@ func (c *FileTypeClient) Delete() *FileTypeDelete { return &FileTypeDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *FileTypeClient) DeleteOne(ft *FileType) *FileTypeDeleteOne { return c.DeleteOneID(ft.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *FileTypeClient) DeleteOneID(id int) *FileTypeDeleteOne { builder := c.Delete().Where(filetype.ID(id)) builder.mutation.id = &id @@ -786,7 +786,7 @@ func (c *GoodsClient) Use(hooks ...Hook) { c.hooks.Goods = append(c.hooks.Goods, hooks...) } -// Create returns a create builder for Goods. +// Create returns a builder for creating a Goods entity. func (c *GoodsClient) Create() *GoodsCreate { mutation := newGoodsMutation(c.config, OpCreate) return &GoodsCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -821,12 +821,12 @@ func (c *GoodsClient) Delete() *GoodsDelete { return &GoodsDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *GoodsClient) DeleteOne(_go *Goods) *GoodsDeleteOne { return c.DeleteOneID(_go.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *GoodsClient) DeleteOneID(id int) *GoodsDeleteOne { builder := c.Delete().Where(goods.ID(id)) builder.mutation.id = &id @@ -876,7 +876,7 @@ func (c *GroupClient) Use(hooks ...Hook) { c.hooks.Group = append(c.hooks.Group, hooks...) } -// Create returns a create builder for Group. +// Create returns a builder for creating a Group entity. func (c *GroupClient) Create() *GroupCreate { mutation := newGroupMutation(c.config, OpCreate) return &GroupCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -911,12 +911,12 @@ func (c *GroupClient) Delete() *GroupDelete { return &GroupDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *GroupClient) DeleteOne(gr *Group) *GroupDeleteOne { return c.DeleteOneID(gr.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *GroupClient) DeleteOneID(id int) *GroupDeleteOne { builder := c.Delete().Where(group.ID(id)) builder.mutation.id = &id @@ -1030,7 +1030,7 @@ func (c *GroupInfoClient) Use(hooks ...Hook) { c.hooks.GroupInfo = append(c.hooks.GroupInfo, hooks...) } -// Create returns a create builder for GroupInfo. +// Create returns a builder for creating a GroupInfo entity. func (c *GroupInfoClient) Create() *GroupInfoCreate { mutation := newGroupInfoMutation(c.config, OpCreate) return &GroupInfoCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -1065,12 +1065,12 @@ func (c *GroupInfoClient) Delete() *GroupInfoDelete { return &GroupInfoDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *GroupInfoClient) DeleteOne(gi *GroupInfo) *GroupInfoDeleteOne { return c.DeleteOneID(gi.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *GroupInfoClient) DeleteOneID(id int) *GroupInfoDeleteOne { builder := c.Delete().Where(groupinfo.ID(id)) builder.mutation.id = &id @@ -1136,7 +1136,7 @@ func (c *ItemClient) Use(hooks ...Hook) { c.hooks.Item = append(c.hooks.Item, hooks...) } -// Create returns a create builder for Item. +// Create returns a builder for creating a Item entity. func (c *ItemClient) Create() *ItemCreate { mutation := newItemMutation(c.config, OpCreate) return &ItemCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -1171,12 +1171,12 @@ func (c *ItemClient) Delete() *ItemDelete { return &ItemDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *ItemClient) DeleteOne(i *Item) *ItemDeleteOne { return c.DeleteOneID(i.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *ItemClient) DeleteOneID(id string) *ItemDeleteOne { builder := c.Delete().Where(item.ID(id)) builder.mutation.id = &id @@ -1226,7 +1226,7 @@ func (c *NodeClient) Use(hooks ...Hook) { c.hooks.Node = append(c.hooks.Node, hooks...) } -// Create returns a create builder for Node. +// Create returns a builder for creating a Node entity. func (c *NodeClient) Create() *NodeCreate { mutation := newNodeMutation(c.config, OpCreate) return &NodeCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -1261,12 +1261,12 @@ func (c *NodeClient) Delete() *NodeDelete { return &NodeDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *NodeClient) DeleteOne(n *Node) *NodeDeleteOne { return c.DeleteOneID(n.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *NodeClient) DeleteOneID(id int) *NodeDeleteOne { builder := c.Delete().Where(node.ID(id)) builder.mutation.id = &id @@ -1348,7 +1348,7 @@ func (c *PetClient) Use(hooks ...Hook) { c.hooks.Pet = append(c.hooks.Pet, hooks...) } -// Create returns a create builder for Pet. +// Create returns a builder for creating a Pet entity. func (c *PetClient) Create() *PetCreate { mutation := newPetMutation(c.config, OpCreate) return &PetCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -1383,12 +1383,12 @@ func (c *PetClient) Delete() *PetDelete { return &PetDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *PetClient) DeleteOne(pe *Pet) *PetDeleteOne { return c.DeleteOneID(pe.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *PetClient) DeleteOneID(id int) *PetDeleteOne { builder := c.Delete().Where(pet.ID(id)) builder.mutation.id = &id @@ -1470,7 +1470,7 @@ func (c *SpecClient) Use(hooks ...Hook) { c.hooks.Spec = append(c.hooks.Spec, hooks...) } -// Create returns a create builder for Spec. +// Create returns a builder for creating a Spec entity. func (c *SpecClient) Create() *SpecCreate { mutation := newSpecMutation(c.config, OpCreate) return &SpecCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -1505,12 +1505,12 @@ func (c *SpecClient) Delete() *SpecDelete { return &SpecDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *SpecClient) DeleteOne(s *Spec) *SpecDeleteOne { return c.DeleteOneID(s.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *SpecClient) DeleteOneID(id int) *SpecDeleteOne { builder := c.Delete().Where(spec.ID(id)) builder.mutation.id = &id @@ -1576,7 +1576,7 @@ func (c *TaskClient) Use(hooks ...Hook) { c.hooks.Task = append(c.hooks.Task, hooks...) } -// Create returns a create builder for Task. +// Create returns a builder for creating a Task entity. func (c *TaskClient) Create() *TaskCreate { mutation := newTaskMutation(c.config, OpCreate) return &TaskCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -1611,12 +1611,12 @@ func (c *TaskClient) Delete() *TaskDelete { return &TaskDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *TaskClient) DeleteOne(t *Task) *TaskDeleteOne { return c.DeleteOneID(t.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *TaskClient) DeleteOneID(id int) *TaskDeleteOne { builder := c.Delete().Where(enttask.ID(id)) builder.mutation.id = &id @@ -1666,7 +1666,7 @@ func (c *UserClient) Use(hooks ...Hook) { c.hooks.User = append(c.hooks.User, hooks...) } -// Create returns a create builder for User. +// Create returns a builder for creating a User entity. func (c *UserClient) Create() *UserCreate { mutation := newUserMutation(c.config, OpCreate) return &UserCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -1701,12 +1701,12 @@ func (c *UserClient) Delete() *UserDelete { return &UserDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *UserClient) DeleteOne(u *User) *UserDeleteOne { return c.DeleteOneID(u.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *UserClient) DeleteOneID(id int) *UserDeleteOne { builder := c.Delete().Where(user.ID(id)) builder.mutation.id = &id diff --git a/entc/integration/ent/comment.go b/entc/integration/ent/comment.go index 078f329474..65e0397c5f 100644 --- a/entc/integration/ent/comment.go +++ b/entc/integration/ent/comment.go @@ -113,16 +113,19 @@ func (c *Comment) Unwrap() *Comment { func (c *Comment) String() string { var builder strings.Builder builder.WriteString("Comment(") - builder.WriteString(fmt.Sprintf("id=%v", c.ID)) - builder.WriteString(", unique_int=") + builder.WriteString(fmt.Sprintf("id=%v, ", c.ID)) + builder.WriteString("unique_int=") builder.WriteString(fmt.Sprintf("%v", c.UniqueInt)) - builder.WriteString(", unique_float=") + builder.WriteString(", ") + builder.WriteString("unique_float=") builder.WriteString(fmt.Sprintf("%v", c.UniqueFloat)) + builder.WriteString(", ") if v := c.NillableInt; v != nil { - builder.WriteString(", nillable_int=") + builder.WriteString("nillable_int=") builder.WriteString(fmt.Sprintf("%v", *v)) } - builder.WriteString(", table=") + builder.WriteString(", ") + builder.WriteString("table=") builder.WriteString(c.Table) builder.WriteByte(')') return builder.String() diff --git a/entc/integration/ent/comment_create.go b/entc/integration/ent/comment_create.go index b60e7b31ca..fc1826f4ab 100644 --- a/entc/integration/ent/comment_create.go +++ b/entc/integration/ent/comment_create.go @@ -547,11 +547,11 @@ func (ccb *CommentCreateBulk) Save(ctx context.Context) ([]*Comment, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/entc/integration/ent/fieldtype.go b/entc/integration/ent/fieldtype.go index f1802a8191..7dd541f1bd 100644 --- a/entc/integration/ent/fieldtype.go +++ b/entc/integration/ent/fieldtype.go @@ -662,160 +662,224 @@ func (ft *FieldType) Unwrap() *FieldType { func (ft *FieldType) String() string { var builder strings.Builder builder.WriteString("FieldType(") - builder.WriteString(fmt.Sprintf("id=%v", ft.ID)) - builder.WriteString(", int=") + builder.WriteString(fmt.Sprintf("id=%v, ", ft.ID)) + builder.WriteString("int=") builder.WriteString(fmt.Sprintf("%v", ft.Int)) - builder.WriteString(", int8=") + builder.WriteString(", ") + builder.WriteString("int8=") builder.WriteString(fmt.Sprintf("%v", ft.Int8)) - builder.WriteString(", int16=") + builder.WriteString(", ") + builder.WriteString("int16=") builder.WriteString(fmt.Sprintf("%v", ft.Int16)) - builder.WriteString(", int32=") + builder.WriteString(", ") + builder.WriteString("int32=") builder.WriteString(fmt.Sprintf("%v", ft.Int32)) - builder.WriteString(", int64=") + builder.WriteString(", ") + builder.WriteString("int64=") builder.WriteString(fmt.Sprintf("%v", ft.Int64)) - builder.WriteString(", optional_int=") + builder.WriteString(", ") + builder.WriteString("optional_int=") builder.WriteString(fmt.Sprintf("%v", ft.OptionalInt)) - builder.WriteString(", optional_int8=") + builder.WriteString(", ") + builder.WriteString("optional_int8=") builder.WriteString(fmt.Sprintf("%v", ft.OptionalInt8)) - builder.WriteString(", optional_int16=") + builder.WriteString(", ") + builder.WriteString("optional_int16=") builder.WriteString(fmt.Sprintf("%v", ft.OptionalInt16)) - builder.WriteString(", optional_int32=") + builder.WriteString(", ") + builder.WriteString("optional_int32=") builder.WriteString(fmt.Sprintf("%v", ft.OptionalInt32)) - builder.WriteString(", optional_int64=") + builder.WriteString(", ") + builder.WriteString("optional_int64=") builder.WriteString(fmt.Sprintf("%v", ft.OptionalInt64)) + builder.WriteString(", ") if v := ft.NillableInt; v != nil { - builder.WriteString(", nillable_int=") + builder.WriteString("nillable_int=") builder.WriteString(fmt.Sprintf("%v", *v)) } + builder.WriteString(", ") if v := ft.NillableInt8; v != nil { - builder.WriteString(", nillable_int8=") + builder.WriteString("nillable_int8=") builder.WriteString(fmt.Sprintf("%v", *v)) } + builder.WriteString(", ") if v := ft.NillableInt16; v != nil { - builder.WriteString(", nillable_int16=") + builder.WriteString("nillable_int16=") builder.WriteString(fmt.Sprintf("%v", *v)) } + builder.WriteString(", ") if v := ft.NillableInt32; v != nil { - builder.WriteString(", nillable_int32=") + builder.WriteString("nillable_int32=") builder.WriteString(fmt.Sprintf("%v", *v)) } + builder.WriteString(", ") if v := ft.NillableInt64; v != nil { - builder.WriteString(", nillable_int64=") + builder.WriteString("nillable_int64=") builder.WriteString(fmt.Sprintf("%v", *v)) } - builder.WriteString(", validate_optional_int32=") + builder.WriteString(", ") + builder.WriteString("validate_optional_int32=") builder.WriteString(fmt.Sprintf("%v", ft.ValidateOptionalInt32)) - builder.WriteString(", optional_uint=") + builder.WriteString(", ") + builder.WriteString("optional_uint=") builder.WriteString(fmt.Sprintf("%v", ft.OptionalUint)) - builder.WriteString(", optional_uint8=") + builder.WriteString(", ") + builder.WriteString("optional_uint8=") builder.WriteString(fmt.Sprintf("%v", ft.OptionalUint8)) - builder.WriteString(", optional_uint16=") + builder.WriteString(", ") + builder.WriteString("optional_uint16=") builder.WriteString(fmt.Sprintf("%v", ft.OptionalUint16)) - builder.WriteString(", optional_uint32=") + builder.WriteString(", ") + builder.WriteString("optional_uint32=") builder.WriteString(fmt.Sprintf("%v", ft.OptionalUint32)) - builder.WriteString(", optional_uint64=") + builder.WriteString(", ") + builder.WriteString("optional_uint64=") builder.WriteString(fmt.Sprintf("%v", ft.OptionalUint64)) - builder.WriteString(", state=") + builder.WriteString(", ") + builder.WriteString("state=") builder.WriteString(fmt.Sprintf("%v", ft.State)) - builder.WriteString(", optional_float=") + builder.WriteString(", ") + builder.WriteString("optional_float=") builder.WriteString(fmt.Sprintf("%v", ft.OptionalFloat)) - builder.WriteString(", optional_float32=") + builder.WriteString(", ") + builder.WriteString("optional_float32=") builder.WriteString(fmt.Sprintf("%v", ft.OptionalFloat32)) - builder.WriteString(", text=") + builder.WriteString(", ") + builder.WriteString("text=") builder.WriteString(ft.Text) - builder.WriteString(", datetime=") + builder.WriteString(", ") + builder.WriteString("datetime=") builder.WriteString(ft.Datetime.Format(time.ANSIC)) - builder.WriteString(", decimal=") + builder.WriteString(", ") + builder.WriteString("decimal=") builder.WriteString(fmt.Sprintf("%v", ft.Decimal)) - builder.WriteString(", link_other=") + builder.WriteString(", ") + builder.WriteString("link_other=") builder.WriteString(fmt.Sprintf("%v", ft.LinkOther)) - builder.WriteString(", link_other_func=") + builder.WriteString(", ") + builder.WriteString("link_other_func=") builder.WriteString(fmt.Sprintf("%v", ft.LinkOtherFunc)) - builder.WriteString(", mac=") + builder.WriteString(", ") + builder.WriteString("mac=") builder.WriteString(fmt.Sprintf("%v", ft.MAC)) - builder.WriteString(", string_array=") + builder.WriteString(", ") + builder.WriteString("string_array=") builder.WriteString(fmt.Sprintf("%v", ft.StringArray)) - builder.WriteString(", password=") + builder.WriteString(", ") + builder.WriteString("password=") + builder.WriteString(", ") if v := ft.StringScanner; v != nil { - builder.WriteString(", string_scanner=") + builder.WriteString("string_scanner=") builder.WriteString(fmt.Sprintf("%v", *v)) } - builder.WriteString(", duration=") + builder.WriteString(", ") + builder.WriteString("duration=") builder.WriteString(fmt.Sprintf("%v", ft.Duration)) - builder.WriteString(", dir=") + builder.WriteString(", ") + builder.WriteString("dir=") builder.WriteString(fmt.Sprintf("%v", ft.Dir)) + builder.WriteString(", ") if v := ft.Ndir; v != nil { - builder.WriteString(", ndir=") + builder.WriteString("ndir=") builder.WriteString(fmt.Sprintf("%v", *v)) } - builder.WriteString(", str=") + builder.WriteString(", ") + builder.WriteString("str=") builder.WriteString(fmt.Sprintf("%v", ft.Str)) + builder.WriteString(", ") if v := ft.NullStr; v != nil { - builder.WriteString(", null_str=") + builder.WriteString("null_str=") builder.WriteString(fmt.Sprintf("%v", *v)) } - builder.WriteString(", link=") + builder.WriteString(", ") + builder.WriteString("link=") builder.WriteString(fmt.Sprintf("%v", ft.Link)) + builder.WriteString(", ") if v := ft.NullLink; v != nil { - builder.WriteString(", null_link=") + builder.WriteString("null_link=") builder.WriteString(fmt.Sprintf("%v", *v)) } - builder.WriteString(", active=") + builder.WriteString(", ") + builder.WriteString("active=") builder.WriteString(fmt.Sprintf("%v", ft.Active)) + builder.WriteString(", ") if v := ft.NullActive; v != nil { - builder.WriteString(", null_active=") + builder.WriteString("null_active=") builder.WriteString(fmt.Sprintf("%v", *v)) } + builder.WriteString(", ") if v := ft.Deleted; v != nil { - builder.WriteString(", deleted=") + builder.WriteString("deleted=") builder.WriteString(fmt.Sprintf("%v", *v)) } - builder.WriteString(", deleted_at=") + builder.WriteString(", ") + builder.WriteString("deleted_at=") builder.WriteString(fmt.Sprintf("%v", ft.DeletedAt)) - builder.WriteString(", raw_data=") + builder.WriteString(", ") + builder.WriteString("raw_data=") builder.WriteString(fmt.Sprintf("%v", ft.RawData)) - builder.WriteString(", sensitive=") - builder.WriteString(", ip=") + builder.WriteString(", ") + builder.WriteString("sensitive=") + builder.WriteString(", ") + builder.WriteString("ip=") builder.WriteString(fmt.Sprintf("%v", ft.IP)) - builder.WriteString(", null_int64=") + builder.WriteString(", ") + builder.WriteString("null_int64=") builder.WriteString(fmt.Sprintf("%v", ft.NullInt64)) - builder.WriteString(", schema_int=") + builder.WriteString(", ") + builder.WriteString("schema_int=") builder.WriteString(fmt.Sprintf("%v", ft.SchemaInt)) - builder.WriteString(", schema_int8=") + builder.WriteString(", ") + builder.WriteString("schema_int8=") builder.WriteString(fmt.Sprintf("%v", ft.SchemaInt8)) - builder.WriteString(", schema_int64=") + builder.WriteString(", ") + builder.WriteString("schema_int64=") builder.WriteString(fmt.Sprintf("%v", ft.SchemaInt64)) - builder.WriteString(", schema_float=") + builder.WriteString(", ") + builder.WriteString("schema_float=") builder.WriteString(fmt.Sprintf("%v", ft.SchemaFloat)) - builder.WriteString(", schema_float32=") + builder.WriteString(", ") + builder.WriteString("schema_float32=") builder.WriteString(fmt.Sprintf("%v", ft.SchemaFloat32)) - builder.WriteString(", null_float=") + builder.WriteString(", ") + builder.WriteString("null_float=") builder.WriteString(fmt.Sprintf("%v", ft.NullFloat)) - builder.WriteString(", role=") + builder.WriteString(", ") + builder.WriteString("role=") builder.WriteString(fmt.Sprintf("%v", ft.Role)) - builder.WriteString(", priority=") + builder.WriteString(", ") + builder.WriteString("priority=") builder.WriteString(fmt.Sprintf("%v", ft.Priority)) - builder.WriteString(", optional_uuid=") + builder.WriteString(", ") + builder.WriteString("optional_uuid=") builder.WriteString(fmt.Sprintf("%v", ft.OptionalUUID)) + builder.WriteString(", ") if v := ft.NillableUUID; v != nil { - builder.WriteString(", nillable_uuid=") + builder.WriteString("nillable_uuid=") builder.WriteString(fmt.Sprintf("%v", *v)) } - builder.WriteString(", strings=") + builder.WriteString(", ") + builder.WriteString("strings=") builder.WriteString(fmt.Sprintf("%v", ft.Strings)) - builder.WriteString(", pair=") + builder.WriteString(", ") + builder.WriteString("pair=") builder.WriteString(fmt.Sprintf("%v", ft.Pair)) + builder.WriteString(", ") if v := ft.NilPair; v != nil { - builder.WriteString(", nil_pair=") + builder.WriteString("nil_pair=") builder.WriteString(fmt.Sprintf("%v", *v)) } - builder.WriteString(", vstring=") + builder.WriteString(", ") + builder.WriteString("vstring=") builder.WriteString(fmt.Sprintf("%v", ft.Vstring)) - builder.WriteString(", triple=") + builder.WriteString(", ") + builder.WriteString("triple=") builder.WriteString(fmt.Sprintf("%v", ft.Triple)) - builder.WriteString(", big_int=") + builder.WriteString(", ") + builder.WriteString("big_int=") builder.WriteString(fmt.Sprintf("%v", ft.BigInt)) - builder.WriteString(", password_other=") + builder.WriteString(", ") + builder.WriteString("password_other=") builder.WriteByte(')') return builder.String() } diff --git a/entc/integration/ent/fieldtype_create.go b/entc/integration/ent/fieldtype_create.go index 7165a64650..c16e047979 100644 --- a/entc/integration/ent/fieldtype_create.go +++ b/entc/integration/ent/fieldtype_create.go @@ -4517,11 +4517,11 @@ func (ftcb *FieldTypeCreateBulk) Save(ctx context.Context) ([]*FieldType, error) return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/entc/integration/ent/file.go b/entc/integration/ent/file.go index 81e358d50d..0d79f9bf02 100644 --- a/entc/integration/ent/file.go +++ b/entc/integration/ent/file.go @@ -221,18 +221,22 @@ func (f *File) Unwrap() *File { func (f *File) String() string { var builder strings.Builder builder.WriteString("File(") - builder.WriteString(fmt.Sprintf("id=%v", f.ID)) - builder.WriteString(", size=") + builder.WriteString(fmt.Sprintf("id=%v, ", f.ID)) + builder.WriteString("size=") builder.WriteString(fmt.Sprintf("%v", f.Size)) - builder.WriteString(", name=") + builder.WriteString(", ") + builder.WriteString("name=") builder.WriteString(f.Name) + builder.WriteString(", ") if v := f.User; v != nil { - builder.WriteString(", user=") + builder.WriteString("user=") builder.WriteString(*v) } - builder.WriteString(", group=") + builder.WriteString(", ") + builder.WriteString("group=") builder.WriteString(f.Group) - builder.WriteString(", op=") + builder.WriteString(", ") + builder.WriteString("op=") builder.WriteString(fmt.Sprintf("%v", f.Op)) builder.WriteByte(')') return builder.String() diff --git a/entc/integration/ent/file_create.go b/entc/integration/ent/file_create.go index 3cae6aa1ef..0a15e9afd0 100644 --- a/entc/integration/ent/file_create.go +++ b/entc/integration/ent/file_create.go @@ -720,11 +720,11 @@ func (fcb *FileCreateBulk) Save(ctx context.Context) ([]*File, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/entc/integration/ent/filetype.go b/entc/integration/ent/filetype.go index 9b9a93e943..cdfe1fa64f 100644 --- a/entc/integration/ent/filetype.go +++ b/entc/integration/ent/filetype.go @@ -128,12 +128,14 @@ func (ft *FileType) Unwrap() *FileType { func (ft *FileType) String() string { var builder strings.Builder builder.WriteString("FileType(") - builder.WriteString(fmt.Sprintf("id=%v", ft.ID)) - builder.WriteString(", name=") + builder.WriteString(fmt.Sprintf("id=%v, ", ft.ID)) + builder.WriteString("name=") builder.WriteString(ft.Name) - builder.WriteString(", type=") + builder.WriteString(", ") + builder.WriteString("type=") builder.WriteString(fmt.Sprintf("%v", ft.Type)) - builder.WriteString(", state=") + builder.WriteString(", ") + builder.WriteString("state=") builder.WriteString(fmt.Sprintf("%v", ft.State)) builder.WriteByte(')') return builder.String() diff --git a/entc/integration/ent/filetype_create.go b/entc/integration/ent/filetype_create.go index 426fbe426d..06d8d90a32 100644 --- a/entc/integration/ent/filetype_create.go +++ b/entc/integration/ent/filetype_create.go @@ -504,11 +504,11 @@ func (ftcb *FileTypeCreateBulk) Save(ctx context.Context) ([]*FileType, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/entc/integration/ent/goods_create.go b/entc/integration/ent/goods_create.go index 05195f52d5..930d7f12e5 100644 --- a/entc/integration/ent/goods_create.go +++ b/entc/integration/ent/goods_create.go @@ -294,11 +294,11 @@ func (gcb *GoodsCreateBulk) Save(ctx context.Context) ([]*Goods, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/entc/integration/ent/group.go b/entc/integration/ent/group.go index c92aef4d99..0862928eea 100644 --- a/entc/integration/ent/group.go +++ b/entc/integration/ent/group.go @@ -215,18 +215,22 @@ func (gr *Group) Unwrap() *Group { func (gr *Group) String() string { var builder strings.Builder builder.WriteString("Group(") - builder.WriteString(fmt.Sprintf("id=%v", gr.ID)) - builder.WriteString(", active=") + builder.WriteString(fmt.Sprintf("id=%v, ", gr.ID)) + builder.WriteString("active=") builder.WriteString(fmt.Sprintf("%v", gr.Active)) - builder.WriteString(", expire=") + builder.WriteString(", ") + builder.WriteString("expire=") builder.WriteString(gr.Expire.Format(time.ANSIC)) + builder.WriteString(", ") if v := gr.Type; v != nil { - builder.WriteString(", type=") + builder.WriteString("type=") builder.WriteString(*v) } - builder.WriteString(", max_users=") + builder.WriteString(", ") + builder.WriteString("max_users=") builder.WriteString(fmt.Sprintf("%v", gr.MaxUsers)) - builder.WriteString(", name=") + builder.WriteString(", ") + builder.WriteString("name=") builder.WriteString(gr.Name) builder.WriteByte(')') return builder.String() diff --git a/entc/integration/ent/group_create.go b/entc/integration/ent/group_create.go index 6b8d0ef695..94210114ea 100644 --- a/entc/integration/ent/group_create.go +++ b/entc/integration/ent/group_create.go @@ -741,11 +741,11 @@ func (gcb *GroupCreateBulk) Save(ctx context.Context) ([]*Group, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/entc/integration/ent/groupinfo.go b/entc/integration/ent/groupinfo.go index f9c961e550..d2dbeb1dfb 100644 --- a/entc/integration/ent/groupinfo.go +++ b/entc/integration/ent/groupinfo.go @@ -120,10 +120,11 @@ func (gi *GroupInfo) Unwrap() *GroupInfo { func (gi *GroupInfo) String() string { var builder strings.Builder builder.WriteString("GroupInfo(") - builder.WriteString(fmt.Sprintf("id=%v", gi.ID)) - builder.WriteString(", desc=") + builder.WriteString(fmt.Sprintf("id=%v, ", gi.ID)) + builder.WriteString("desc=") builder.WriteString(gi.Desc) - builder.WriteString(", max_users=") + builder.WriteString(", ") + builder.WriteString("max_users=") builder.WriteString(fmt.Sprintf("%v", gi.MaxUsers)) builder.WriteByte(')') return builder.String() diff --git a/entc/integration/ent/groupinfo_create.go b/entc/integration/ent/groupinfo_create.go index b690e97a96..c47466b1fa 100644 --- a/entc/integration/ent/groupinfo_create.go +++ b/entc/integration/ent/groupinfo_create.go @@ -452,11 +452,11 @@ func (gicb *GroupInfoCreateBulk) Save(ctx context.Context) ([]*GroupInfo, error) return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/entc/integration/ent/item.go b/entc/integration/ent/item.go index 7023be7a2f..8fec1bb58a 100644 --- a/entc/integration/ent/item.go +++ b/entc/integration/ent/item.go @@ -84,8 +84,8 @@ func (i *Item) Unwrap() *Item { func (i *Item) String() string { var builder strings.Builder builder.WriteString("Item(") - builder.WriteString(fmt.Sprintf("id=%v", i.ID)) - builder.WriteString(", text=") + builder.WriteString(fmt.Sprintf("id=%v, ", i.ID)) + builder.WriteString("text=") builder.WriteString(i.Text) builder.WriteByte(')') return builder.String() diff --git a/entc/integration/ent/node.go b/entc/integration/ent/node.go index ed501abe70..b171ef12cc 100644 --- a/entc/integration/ent/node.go +++ b/entc/integration/ent/node.go @@ -146,8 +146,8 @@ func (n *Node) Unwrap() *Node { func (n *Node) String() string { var builder strings.Builder builder.WriteString("Node(") - builder.WriteString(fmt.Sprintf("id=%v", n.ID)) - builder.WriteString(", value=") + builder.WriteString(fmt.Sprintf("id=%v, ", n.ID)) + builder.WriteString("value=") builder.WriteString(fmt.Sprintf("%v", n.Value)) builder.WriteByte(')') return builder.String() diff --git a/entc/integration/ent/node_create.go b/entc/integration/ent/node_create.go index ecc5fd8adb..fc4b92471c 100644 --- a/entc/integration/ent/node_create.go +++ b/entc/integration/ent/node_create.go @@ -451,11 +451,11 @@ func (ncb *NodeCreateBulk) Save(ctx context.Context) ([]*Node, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/entc/integration/ent/pet.go b/entc/integration/ent/pet.go index 9ef4994829..efce573ba7 100644 --- a/entc/integration/ent/pet.go +++ b/entc/integration/ent/pet.go @@ -188,14 +188,17 @@ func (pe *Pet) Unwrap() *Pet { func (pe *Pet) String() string { var builder strings.Builder builder.WriteString("Pet(") - builder.WriteString(fmt.Sprintf("id=%v", pe.ID)) - builder.WriteString(", age=") + builder.WriteString(fmt.Sprintf("id=%v, ", pe.ID)) + builder.WriteString("age=") builder.WriteString(fmt.Sprintf("%v", pe.Age)) - builder.WriteString(", name=") + builder.WriteString(", ") + builder.WriteString("name=") builder.WriteString(pe.Name) - builder.WriteString(", uuid=") + builder.WriteString(", ") + builder.WriteString("uuid=") builder.WriteString(fmt.Sprintf("%v", pe.UUID)) - builder.WriteString(", nickname=") + builder.WriteString(", ") + builder.WriteString("nickname=") builder.WriteString(pe.Nickname) builder.WriteByte(')') return builder.String() diff --git a/entc/integration/ent/pet_create.go b/entc/integration/ent/pet_create.go index b4dbe3aed3..25a8e88927 100644 --- a/entc/integration/ent/pet_create.go +++ b/entc/integration/ent/pet_create.go @@ -619,11 +619,11 @@ func (pcb *PetCreateBulk) Save(ctx context.Context) ([]*Pet, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/entc/integration/ent/spec_create.go b/entc/integration/ent/spec_create.go index a81f1aabb6..4f2a98d102 100644 --- a/entc/integration/ent/spec_create.go +++ b/entc/integration/ent/spec_create.go @@ -329,11 +329,11 @@ func (scb *SpecCreateBulk) Save(ctx context.Context) ([]*Spec, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/entc/integration/ent/task.go b/entc/integration/ent/task.go index 21a4635aa2..d3969dd6eb 100644 --- a/entc/integration/ent/task.go +++ b/entc/integration/ent/task.go @@ -86,8 +86,8 @@ func (t *Task) Unwrap() *Task { func (t *Task) String() string { var builder strings.Builder builder.WriteString("Task(") - builder.WriteString(fmt.Sprintf("id=%v", t.ID)) - builder.WriteString(", priority=") + builder.WriteString(fmt.Sprintf("id=%v, ", t.ID)) + builder.WriteString("priority=") builder.WriteString(fmt.Sprintf("%v", t.Priority)) builder.WriteByte(')') return builder.String() diff --git a/entc/integration/ent/task_create.go b/entc/integration/ent/task_create.go index f9413b0969..e6a8c2822b 100644 --- a/entc/integration/ent/task_create.go +++ b/entc/integration/ent/task_create.go @@ -381,11 +381,11 @@ func (tcb *TaskCreateBulk) Save(ctx context.Context) ([]*Task, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/entc/integration/ent/user.go b/entc/integration/ent/user.go index 08034c4b21..7e9159e453 100644 --- a/entc/integration/ent/user.go +++ b/entc/integration/ent/user.go @@ -404,27 +404,37 @@ func (u *User) Unwrap() *User { func (u *User) String() string { var builder strings.Builder builder.WriteString("User(") - builder.WriteString(fmt.Sprintf("id=%v", u.ID)) - builder.WriteString(", optional_int=") + builder.WriteString(fmt.Sprintf("id=%v, ", u.ID)) + builder.WriteString("optional_int=") builder.WriteString(fmt.Sprintf("%v", u.OptionalInt)) - builder.WriteString(", age=") + builder.WriteString(", ") + builder.WriteString("age=") builder.WriteString(fmt.Sprintf("%v", u.Age)) - builder.WriteString(", name=") + builder.WriteString(", ") + builder.WriteString("name=") builder.WriteString(u.Name) - builder.WriteString(", last=") + builder.WriteString(", ") + builder.WriteString("last=") builder.WriteString(u.Last) - builder.WriteString(", nickname=") + builder.WriteString(", ") + builder.WriteString("nickname=") builder.WriteString(u.Nickname) - builder.WriteString(", address=") + builder.WriteString(", ") + builder.WriteString("address=") builder.WriteString(u.Address) - builder.WriteString(", phone=") + builder.WriteString(", ") + builder.WriteString("phone=") builder.WriteString(u.Phone) - builder.WriteString(", password=") - builder.WriteString(", role=") + builder.WriteString(", ") + builder.WriteString("password=") + builder.WriteString(", ") + builder.WriteString("role=") builder.WriteString(fmt.Sprintf("%v", u.Role)) - builder.WriteString(", employment=") + builder.WriteString(", ") + builder.WriteString("employment=") builder.WriteString(fmt.Sprintf("%v", u.Employment)) - builder.WriteString(", SSOCert=") + builder.WriteString(", ") + builder.WriteString("SSOCert=") builder.WriteString(u.SSOCert) builder.WriteByte(')') return builder.String() diff --git a/entc/integration/ent/user_create.go b/entc/integration/ent/user_create.go index c832f54474..8a2dedaf05 100644 --- a/entc/integration/ent/user_create.go +++ b/entc/integration/ent/user_create.go @@ -1364,11 +1364,11 @@ func (ucb *UserCreateBulk) Save(ctx context.Context) ([]*User, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/entc/integration/gremlin/ent/card.go b/entc/integration/gremlin/ent/card.go index 2d0a7d0775..090c80e620 100644 --- a/entc/integration/gremlin/ent/card.go +++ b/entc/integration/gremlin/ent/card.go @@ -130,16 +130,20 @@ func (c *Card) Unwrap() *Card { func (c *Card) String() string { var builder strings.Builder builder.WriteString("Card(") - builder.WriteString(fmt.Sprintf("id=%v", c.ID)) - builder.WriteString(", create_time=") + builder.WriteString(fmt.Sprintf("id=%v, ", c.ID)) + builder.WriteString("create_time=") builder.WriteString(c.CreateTime.Format(time.ANSIC)) - builder.WriteString(", update_time=") + builder.WriteString(", ") + builder.WriteString("update_time=") builder.WriteString(c.UpdateTime.Format(time.ANSIC)) - builder.WriteString(", balance=") + builder.WriteString(", ") + builder.WriteString("balance=") builder.WriteString(fmt.Sprintf("%v", c.Balance)) - builder.WriteString(", number=") + builder.WriteString(", ") + builder.WriteString("number=") builder.WriteString(c.Number) - builder.WriteString(", name=") + builder.WriteString(", ") + builder.WriteString("name=") builder.WriteString(c.Name) builder.WriteByte(')') return builder.String() diff --git a/entc/integration/gremlin/ent/client.go b/entc/integration/gremlin/ent/client.go index e0d7db3546..c40fefe32b 100644 --- a/entc/integration/gremlin/ent/client.go +++ b/entc/integration/gremlin/ent/client.go @@ -213,7 +213,7 @@ func (c *CardClient) Use(hooks ...Hook) { c.hooks.Card = append(c.hooks.Card, hooks...) } -// Create returns a create builder for Card. +// Create returns a builder for creating a Card entity. func (c *CardClient) Create() *CardCreate { mutation := newCardMutation(c.config, OpCreate) return &CardCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -248,12 +248,12 @@ func (c *CardClient) Delete() *CardDelete { return &CardDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *CardClient) DeleteOne(ca *Card) *CardDeleteOne { return c.DeleteOneID(ca.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *CardClient) DeleteOneID(id string) *CardDeleteOne { builder := c.Delete().Where(card.ID(id)) builder.mutation.id = &id @@ -325,7 +325,7 @@ func (c *CommentClient) Use(hooks ...Hook) { c.hooks.Comment = append(c.hooks.Comment, hooks...) } -// Create returns a create builder for Comment. +// Create returns a builder for creating a Comment entity. func (c *CommentClient) Create() *CommentCreate { mutation := newCommentMutation(c.config, OpCreate) return &CommentCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -360,12 +360,12 @@ func (c *CommentClient) Delete() *CommentDelete { return &CommentDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *CommentClient) DeleteOne(co *Comment) *CommentDeleteOne { return c.DeleteOneID(co.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *CommentClient) DeleteOneID(id string) *CommentDeleteOne { builder := c.Delete().Where(comment.ID(id)) builder.mutation.id = &id @@ -415,7 +415,7 @@ func (c *FieldTypeClient) Use(hooks ...Hook) { c.hooks.FieldType = append(c.hooks.FieldType, hooks...) } -// Create returns a create builder for FieldType. +// Create returns a builder for creating a FieldType entity. func (c *FieldTypeClient) Create() *FieldTypeCreate { mutation := newFieldTypeMutation(c.config, OpCreate) return &FieldTypeCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -450,12 +450,12 @@ func (c *FieldTypeClient) Delete() *FieldTypeDelete { return &FieldTypeDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *FieldTypeClient) DeleteOne(ft *FieldType) *FieldTypeDeleteOne { return c.DeleteOneID(ft.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *FieldTypeClient) DeleteOneID(id string) *FieldTypeDeleteOne { builder := c.Delete().Where(fieldtype.ID(id)) builder.mutation.id = &id @@ -505,7 +505,7 @@ func (c *FileClient) Use(hooks ...Hook) { c.hooks.File = append(c.hooks.File, hooks...) } -// Create returns a create builder for File. +// Create returns a builder for creating a File entity. func (c *FileClient) Create() *FileCreate { mutation := newFileMutation(c.config, OpCreate) return &FileCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -540,12 +540,12 @@ func (c *FileClient) Delete() *FileDelete { return &FileDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *FileClient) DeleteOne(f *File) *FileDeleteOne { return c.DeleteOneID(f.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *FileClient) DeleteOneID(id string) *FileDeleteOne { builder := c.Delete().Where(file.ID(id)) builder.mutation.id = &id @@ -628,7 +628,7 @@ func (c *FileTypeClient) Use(hooks ...Hook) { c.hooks.FileType = append(c.hooks.FileType, hooks...) } -// Create returns a create builder for FileType. +// Create returns a builder for creating a FileType entity. func (c *FileTypeClient) Create() *FileTypeCreate { mutation := newFileTypeMutation(c.config, OpCreate) return &FileTypeCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -663,12 +663,12 @@ func (c *FileTypeClient) Delete() *FileTypeDelete { return &FileTypeDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *FileTypeClient) DeleteOne(ft *FileType) *FileTypeDeleteOne { return c.DeleteOneID(ft.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *FileTypeClient) DeleteOneID(id string) *FileTypeDeleteOne { builder := c.Delete().Where(filetype.ID(id)) builder.mutation.id = &id @@ -729,7 +729,7 @@ func (c *GoodsClient) Use(hooks ...Hook) { c.hooks.Goods = append(c.hooks.Goods, hooks...) } -// Create returns a create builder for Goods. +// Create returns a builder for creating a Goods entity. func (c *GoodsClient) Create() *GoodsCreate { mutation := newGoodsMutation(c.config, OpCreate) return &GoodsCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -764,12 +764,12 @@ func (c *GoodsClient) Delete() *GoodsDelete { return &GoodsDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *GoodsClient) DeleteOne(_go *Goods) *GoodsDeleteOne { return c.DeleteOneID(_go.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *GoodsClient) DeleteOneID(id string) *GoodsDeleteOne { builder := c.Delete().Where(goods.ID(id)) builder.mutation.id = &id @@ -819,7 +819,7 @@ func (c *GroupClient) Use(hooks ...Hook) { c.hooks.Group = append(c.hooks.Group, hooks...) } -// Create returns a create builder for Group. +// Create returns a builder for creating a Group entity. func (c *GroupClient) Create() *GroupCreate { mutation := newGroupMutation(c.config, OpCreate) return &GroupCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -854,12 +854,12 @@ func (c *GroupClient) Delete() *GroupDelete { return &GroupDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *GroupClient) DeleteOne(gr *Group) *GroupDeleteOne { return c.DeleteOneID(gr.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *GroupClient) DeleteOneID(id string) *GroupDeleteOne { builder := c.Delete().Where(group.ID(id)) builder.mutation.id = &id @@ -953,7 +953,7 @@ func (c *GroupInfoClient) Use(hooks ...Hook) { c.hooks.GroupInfo = append(c.hooks.GroupInfo, hooks...) } -// Create returns a create builder for GroupInfo. +// Create returns a builder for creating a GroupInfo entity. func (c *GroupInfoClient) Create() *GroupInfoCreate { mutation := newGroupInfoMutation(c.config, OpCreate) return &GroupInfoCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -988,12 +988,12 @@ func (c *GroupInfoClient) Delete() *GroupInfoDelete { return &GroupInfoDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *GroupInfoClient) DeleteOne(gi *GroupInfo) *GroupInfoDeleteOne { return c.DeleteOneID(gi.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *GroupInfoClient) DeleteOneID(id string) *GroupInfoDeleteOne { builder := c.Delete().Where(groupinfo.ID(id)) builder.mutation.id = &id @@ -1054,7 +1054,7 @@ func (c *ItemClient) Use(hooks ...Hook) { c.hooks.Item = append(c.hooks.Item, hooks...) } -// Create returns a create builder for Item. +// Create returns a builder for creating a Item entity. func (c *ItemClient) Create() *ItemCreate { mutation := newItemMutation(c.config, OpCreate) return &ItemCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -1089,12 +1089,12 @@ func (c *ItemClient) Delete() *ItemDelete { return &ItemDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *ItemClient) DeleteOne(i *Item) *ItemDeleteOne { return c.DeleteOneID(i.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *ItemClient) DeleteOneID(id string) *ItemDeleteOne { builder := c.Delete().Where(item.ID(id)) builder.mutation.id = &id @@ -1144,7 +1144,7 @@ func (c *NodeClient) Use(hooks ...Hook) { c.hooks.Node = append(c.hooks.Node, hooks...) } -// Create returns a create builder for Node. +// Create returns a builder for creating a Node entity. func (c *NodeClient) Create() *NodeCreate { mutation := newNodeMutation(c.config, OpCreate) return &NodeCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -1179,12 +1179,12 @@ func (c *NodeClient) Delete() *NodeDelete { return &NodeDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *NodeClient) DeleteOne(n *Node) *NodeDeleteOne { return c.DeleteOneID(n.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *NodeClient) DeleteOneID(id string) *NodeDeleteOne { builder := c.Delete().Where(node.ID(id)) builder.mutation.id = &id @@ -1256,7 +1256,7 @@ func (c *PetClient) Use(hooks ...Hook) { c.hooks.Pet = append(c.hooks.Pet, hooks...) } -// Create returns a create builder for Pet. +// Create returns a builder for creating a Pet entity. func (c *PetClient) Create() *PetCreate { mutation := newPetMutation(c.config, OpCreate) return &PetCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -1291,12 +1291,12 @@ func (c *PetClient) Delete() *PetDelete { return &PetDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *PetClient) DeleteOne(pe *Pet) *PetDeleteOne { return c.DeleteOneID(pe.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *PetClient) DeleteOneID(id string) *PetDeleteOne { builder := c.Delete().Where(pet.ID(id)) builder.mutation.id = &id @@ -1368,7 +1368,7 @@ func (c *SpecClient) Use(hooks ...Hook) { c.hooks.Spec = append(c.hooks.Spec, hooks...) } -// Create returns a create builder for Spec. +// Create returns a builder for creating a Spec entity. func (c *SpecClient) Create() *SpecCreate { mutation := newSpecMutation(c.config, OpCreate) return &SpecCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -1403,12 +1403,12 @@ func (c *SpecClient) Delete() *SpecDelete { return &SpecDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *SpecClient) DeleteOne(s *Spec) *SpecDeleteOne { return c.DeleteOneID(s.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *SpecClient) DeleteOneID(id string) *SpecDeleteOne { builder := c.Delete().Where(spec.ID(id)) builder.mutation.id = &id @@ -1469,7 +1469,7 @@ func (c *TaskClient) Use(hooks ...Hook) { c.hooks.Task = append(c.hooks.Task, hooks...) } -// Create returns a create builder for Task. +// Create returns a builder for creating a Task entity. func (c *TaskClient) Create() *TaskCreate { mutation := newTaskMutation(c.config, OpCreate) return &TaskCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -1504,12 +1504,12 @@ func (c *TaskClient) Delete() *TaskDelete { return &TaskDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *TaskClient) DeleteOne(t *Task) *TaskDeleteOne { return c.DeleteOneID(t.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *TaskClient) DeleteOneID(id string) *TaskDeleteOne { builder := c.Delete().Where(enttask.ID(id)) builder.mutation.id = &id @@ -1559,7 +1559,7 @@ func (c *UserClient) Use(hooks ...Hook) { c.hooks.User = append(c.hooks.User, hooks...) } -// Create returns a create builder for User. +// Create returns a builder for creating a User entity. func (c *UserClient) Create() *UserCreate { mutation := newUserMutation(c.config, OpCreate) return &UserCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -1594,12 +1594,12 @@ func (c *UserClient) Delete() *UserDelete { return &UserDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *UserClient) DeleteOne(u *User) *UserDeleteOne { return c.DeleteOneID(u.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *UserClient) DeleteOneID(id string) *UserDeleteOne { builder := c.Delete().Where(user.ID(id)) builder.mutation.id = &id diff --git a/entc/integration/gremlin/ent/comment.go b/entc/integration/gremlin/ent/comment.go index 6aec019334..e942517212 100644 --- a/entc/integration/gremlin/ent/comment.go +++ b/entc/integration/gremlin/ent/comment.go @@ -74,16 +74,19 @@ func (c *Comment) Unwrap() *Comment { func (c *Comment) String() string { var builder strings.Builder builder.WriteString("Comment(") - builder.WriteString(fmt.Sprintf("id=%v", c.ID)) - builder.WriteString(", unique_int=") + builder.WriteString(fmt.Sprintf("id=%v, ", c.ID)) + builder.WriteString("unique_int=") builder.WriteString(fmt.Sprintf("%v", c.UniqueInt)) - builder.WriteString(", unique_float=") + builder.WriteString(", ") + builder.WriteString("unique_float=") builder.WriteString(fmt.Sprintf("%v", c.UniqueFloat)) + builder.WriteString(", ") if v := c.NillableInt; v != nil { - builder.WriteString(", nillable_int=") + builder.WriteString("nillable_int=") builder.WriteString(fmt.Sprintf("%v", *v)) } - builder.WriteString(", table=") + builder.WriteString(", ") + builder.WriteString("table=") builder.WriteString(c.Table) builder.WriteByte(')') return builder.String() diff --git a/entc/integration/gremlin/ent/fieldtype.go b/entc/integration/gremlin/ent/fieldtype.go index ad39736341..c6c2ff22bd 100644 --- a/entc/integration/gremlin/ent/fieldtype.go +++ b/entc/integration/gremlin/ent/fieldtype.go @@ -326,160 +326,224 @@ func (ft *FieldType) Unwrap() *FieldType { func (ft *FieldType) String() string { var builder strings.Builder builder.WriteString("FieldType(") - builder.WriteString(fmt.Sprintf("id=%v", ft.ID)) - builder.WriteString(", int=") + builder.WriteString(fmt.Sprintf("id=%v, ", ft.ID)) + builder.WriteString("int=") builder.WriteString(fmt.Sprintf("%v", ft.Int)) - builder.WriteString(", int8=") + builder.WriteString(", ") + builder.WriteString("int8=") builder.WriteString(fmt.Sprintf("%v", ft.Int8)) - builder.WriteString(", int16=") + builder.WriteString(", ") + builder.WriteString("int16=") builder.WriteString(fmt.Sprintf("%v", ft.Int16)) - builder.WriteString(", int32=") + builder.WriteString(", ") + builder.WriteString("int32=") builder.WriteString(fmt.Sprintf("%v", ft.Int32)) - builder.WriteString(", int64=") + builder.WriteString(", ") + builder.WriteString("int64=") builder.WriteString(fmt.Sprintf("%v", ft.Int64)) - builder.WriteString(", optional_int=") + builder.WriteString(", ") + builder.WriteString("optional_int=") builder.WriteString(fmt.Sprintf("%v", ft.OptionalInt)) - builder.WriteString(", optional_int8=") + builder.WriteString(", ") + builder.WriteString("optional_int8=") builder.WriteString(fmt.Sprintf("%v", ft.OptionalInt8)) - builder.WriteString(", optional_int16=") + builder.WriteString(", ") + builder.WriteString("optional_int16=") builder.WriteString(fmt.Sprintf("%v", ft.OptionalInt16)) - builder.WriteString(", optional_int32=") + builder.WriteString(", ") + builder.WriteString("optional_int32=") builder.WriteString(fmt.Sprintf("%v", ft.OptionalInt32)) - builder.WriteString(", optional_int64=") + builder.WriteString(", ") + builder.WriteString("optional_int64=") builder.WriteString(fmt.Sprintf("%v", ft.OptionalInt64)) + builder.WriteString(", ") if v := ft.NillableInt; v != nil { - builder.WriteString(", nillable_int=") + builder.WriteString("nillable_int=") builder.WriteString(fmt.Sprintf("%v", *v)) } + builder.WriteString(", ") if v := ft.NillableInt8; v != nil { - builder.WriteString(", nillable_int8=") + builder.WriteString("nillable_int8=") builder.WriteString(fmt.Sprintf("%v", *v)) } + builder.WriteString(", ") if v := ft.NillableInt16; v != nil { - builder.WriteString(", nillable_int16=") + builder.WriteString("nillable_int16=") builder.WriteString(fmt.Sprintf("%v", *v)) } + builder.WriteString(", ") if v := ft.NillableInt32; v != nil { - builder.WriteString(", nillable_int32=") + builder.WriteString("nillable_int32=") builder.WriteString(fmt.Sprintf("%v", *v)) } + builder.WriteString(", ") if v := ft.NillableInt64; v != nil { - builder.WriteString(", nillable_int64=") + builder.WriteString("nillable_int64=") builder.WriteString(fmt.Sprintf("%v", *v)) } - builder.WriteString(", validate_optional_int32=") + builder.WriteString(", ") + builder.WriteString("validate_optional_int32=") builder.WriteString(fmt.Sprintf("%v", ft.ValidateOptionalInt32)) - builder.WriteString(", optional_uint=") + builder.WriteString(", ") + builder.WriteString("optional_uint=") builder.WriteString(fmt.Sprintf("%v", ft.OptionalUint)) - builder.WriteString(", optional_uint8=") + builder.WriteString(", ") + builder.WriteString("optional_uint8=") builder.WriteString(fmt.Sprintf("%v", ft.OptionalUint8)) - builder.WriteString(", optional_uint16=") + builder.WriteString(", ") + builder.WriteString("optional_uint16=") builder.WriteString(fmt.Sprintf("%v", ft.OptionalUint16)) - builder.WriteString(", optional_uint32=") + builder.WriteString(", ") + builder.WriteString("optional_uint32=") builder.WriteString(fmt.Sprintf("%v", ft.OptionalUint32)) - builder.WriteString(", optional_uint64=") + builder.WriteString(", ") + builder.WriteString("optional_uint64=") builder.WriteString(fmt.Sprintf("%v", ft.OptionalUint64)) - builder.WriteString(", state=") + builder.WriteString(", ") + builder.WriteString("state=") builder.WriteString(fmt.Sprintf("%v", ft.State)) - builder.WriteString(", optional_float=") + builder.WriteString(", ") + builder.WriteString("optional_float=") builder.WriteString(fmt.Sprintf("%v", ft.OptionalFloat)) - builder.WriteString(", optional_float32=") + builder.WriteString(", ") + builder.WriteString("optional_float32=") builder.WriteString(fmt.Sprintf("%v", ft.OptionalFloat32)) - builder.WriteString(", text=") + builder.WriteString(", ") + builder.WriteString("text=") builder.WriteString(ft.Text) - builder.WriteString(", datetime=") + builder.WriteString(", ") + builder.WriteString("datetime=") builder.WriteString(ft.Datetime.Format(time.ANSIC)) - builder.WriteString(", decimal=") + builder.WriteString(", ") + builder.WriteString("decimal=") builder.WriteString(fmt.Sprintf("%v", ft.Decimal)) - builder.WriteString(", link_other=") + builder.WriteString(", ") + builder.WriteString("link_other=") builder.WriteString(fmt.Sprintf("%v", ft.LinkOther)) - builder.WriteString(", link_other_func=") + builder.WriteString(", ") + builder.WriteString("link_other_func=") builder.WriteString(fmt.Sprintf("%v", ft.LinkOtherFunc)) - builder.WriteString(", mac=") + builder.WriteString(", ") + builder.WriteString("mac=") builder.WriteString(fmt.Sprintf("%v", ft.MAC)) - builder.WriteString(", string_array=") + builder.WriteString(", ") + builder.WriteString("string_array=") builder.WriteString(fmt.Sprintf("%v", ft.StringArray)) - builder.WriteString(", password=") + builder.WriteString(", ") + builder.WriteString("password=") + builder.WriteString(", ") if v := ft.StringScanner; v != nil { - builder.WriteString(", string_scanner=") + builder.WriteString("string_scanner=") builder.WriteString(fmt.Sprintf("%v", *v)) } - builder.WriteString(", duration=") + builder.WriteString(", ") + builder.WriteString("duration=") builder.WriteString(fmt.Sprintf("%v", ft.Duration)) - builder.WriteString(", dir=") + builder.WriteString(", ") + builder.WriteString("dir=") builder.WriteString(fmt.Sprintf("%v", ft.Dir)) + builder.WriteString(", ") if v := ft.Ndir; v != nil { - builder.WriteString(", ndir=") + builder.WriteString("ndir=") builder.WriteString(fmt.Sprintf("%v", *v)) } - builder.WriteString(", str=") + builder.WriteString(", ") + builder.WriteString("str=") builder.WriteString(fmt.Sprintf("%v", ft.Str)) + builder.WriteString(", ") if v := ft.NullStr; v != nil { - builder.WriteString(", null_str=") + builder.WriteString("null_str=") builder.WriteString(fmt.Sprintf("%v", *v)) } - builder.WriteString(", link=") + builder.WriteString(", ") + builder.WriteString("link=") builder.WriteString(fmt.Sprintf("%v", ft.Link)) + builder.WriteString(", ") if v := ft.NullLink; v != nil { - builder.WriteString(", null_link=") + builder.WriteString("null_link=") builder.WriteString(fmt.Sprintf("%v", *v)) } - builder.WriteString(", active=") + builder.WriteString(", ") + builder.WriteString("active=") builder.WriteString(fmt.Sprintf("%v", ft.Active)) + builder.WriteString(", ") if v := ft.NullActive; v != nil { - builder.WriteString(", null_active=") + builder.WriteString("null_active=") builder.WriteString(fmt.Sprintf("%v", *v)) } + builder.WriteString(", ") if v := ft.Deleted; v != nil { - builder.WriteString(", deleted=") + builder.WriteString("deleted=") builder.WriteString(fmt.Sprintf("%v", *v)) } - builder.WriteString(", deleted_at=") + builder.WriteString(", ") + builder.WriteString("deleted_at=") builder.WriteString(fmt.Sprintf("%v", ft.DeletedAt)) - builder.WriteString(", raw_data=") + builder.WriteString(", ") + builder.WriteString("raw_data=") builder.WriteString(fmt.Sprintf("%v", ft.RawData)) - builder.WriteString(", sensitive=") - builder.WriteString(", ip=") + builder.WriteString(", ") + builder.WriteString("sensitive=") + builder.WriteString(", ") + builder.WriteString("ip=") builder.WriteString(fmt.Sprintf("%v", ft.IP)) - builder.WriteString(", null_int64=") + builder.WriteString(", ") + builder.WriteString("null_int64=") builder.WriteString(fmt.Sprintf("%v", ft.NullInt64)) - builder.WriteString(", schema_int=") + builder.WriteString(", ") + builder.WriteString("schema_int=") builder.WriteString(fmt.Sprintf("%v", ft.SchemaInt)) - builder.WriteString(", schema_int8=") + builder.WriteString(", ") + builder.WriteString("schema_int8=") builder.WriteString(fmt.Sprintf("%v", ft.SchemaInt8)) - builder.WriteString(", schema_int64=") + builder.WriteString(", ") + builder.WriteString("schema_int64=") builder.WriteString(fmt.Sprintf("%v", ft.SchemaInt64)) - builder.WriteString(", schema_float=") + builder.WriteString(", ") + builder.WriteString("schema_float=") builder.WriteString(fmt.Sprintf("%v", ft.SchemaFloat)) - builder.WriteString(", schema_float32=") + builder.WriteString(", ") + builder.WriteString("schema_float32=") builder.WriteString(fmt.Sprintf("%v", ft.SchemaFloat32)) - builder.WriteString(", null_float=") + builder.WriteString(", ") + builder.WriteString("null_float=") builder.WriteString(fmt.Sprintf("%v", ft.NullFloat)) - builder.WriteString(", role=") + builder.WriteString(", ") + builder.WriteString("role=") builder.WriteString(fmt.Sprintf("%v", ft.Role)) - builder.WriteString(", priority=") + builder.WriteString(", ") + builder.WriteString("priority=") builder.WriteString(fmt.Sprintf("%v", ft.Priority)) - builder.WriteString(", optional_uuid=") + builder.WriteString(", ") + builder.WriteString("optional_uuid=") builder.WriteString(fmt.Sprintf("%v", ft.OptionalUUID)) + builder.WriteString(", ") if v := ft.NillableUUID; v != nil { - builder.WriteString(", nillable_uuid=") + builder.WriteString("nillable_uuid=") builder.WriteString(fmt.Sprintf("%v", *v)) } - builder.WriteString(", strings=") + builder.WriteString(", ") + builder.WriteString("strings=") builder.WriteString(fmt.Sprintf("%v", ft.Strings)) - builder.WriteString(", pair=") + builder.WriteString(", ") + builder.WriteString("pair=") builder.WriteString(fmt.Sprintf("%v", ft.Pair)) + builder.WriteString(", ") if v := ft.NilPair; v != nil { - builder.WriteString(", nil_pair=") + builder.WriteString("nil_pair=") builder.WriteString(fmt.Sprintf("%v", *v)) } - builder.WriteString(", vstring=") + builder.WriteString(", ") + builder.WriteString("vstring=") builder.WriteString(fmt.Sprintf("%v", ft.Vstring)) - builder.WriteString(", triple=") + builder.WriteString(", ") + builder.WriteString("triple=") builder.WriteString(fmt.Sprintf("%v", ft.Triple)) - builder.WriteString(", big_int=") + builder.WriteString(", ") + builder.WriteString("big_int=") builder.WriteString(fmt.Sprintf("%v", ft.BigInt)) - builder.WriteString(", password_other=") + builder.WriteString(", ") + builder.WriteString("password_other=") builder.WriteByte(')') return builder.String() } diff --git a/entc/integration/gremlin/ent/file.go b/entc/integration/gremlin/ent/file.go index 49ada0a6a7..46719a4d23 100644 --- a/entc/integration/gremlin/ent/file.go +++ b/entc/integration/gremlin/ent/file.go @@ -148,18 +148,22 @@ func (f *File) Unwrap() *File { func (f *File) String() string { var builder strings.Builder builder.WriteString("File(") - builder.WriteString(fmt.Sprintf("id=%v", f.ID)) - builder.WriteString(", size=") + builder.WriteString(fmt.Sprintf("id=%v, ", f.ID)) + builder.WriteString("size=") builder.WriteString(fmt.Sprintf("%v", f.Size)) - builder.WriteString(", name=") + builder.WriteString(", ") + builder.WriteString("name=") builder.WriteString(f.Name) + builder.WriteString(", ") if v := f.User; v != nil { - builder.WriteString(", user=") + builder.WriteString("user=") builder.WriteString(*v) } - builder.WriteString(", group=") + builder.WriteString(", ") + builder.WriteString("group=") builder.WriteString(f.Group) - builder.WriteString(", op=") + builder.WriteString(", ") + builder.WriteString("op=") builder.WriteString(fmt.Sprintf("%v", f.Op)) builder.WriteByte(')') return builder.String() diff --git a/entc/integration/gremlin/ent/filetype.go b/entc/integration/gremlin/ent/filetype.go index 198eb96af3..a59dea290e 100644 --- a/entc/integration/gremlin/ent/filetype.go +++ b/entc/integration/gremlin/ent/filetype.go @@ -97,12 +97,14 @@ func (ft *FileType) Unwrap() *FileType { func (ft *FileType) String() string { var builder strings.Builder builder.WriteString("FileType(") - builder.WriteString(fmt.Sprintf("id=%v", ft.ID)) - builder.WriteString(", name=") + builder.WriteString(fmt.Sprintf("id=%v, ", ft.ID)) + builder.WriteString("name=") builder.WriteString(ft.Name) - builder.WriteString(", type=") + builder.WriteString(", ") + builder.WriteString("type=") builder.WriteString(fmt.Sprintf("%v", ft.Type)) - builder.WriteString(", state=") + builder.WriteString(", ") + builder.WriteString("state=") builder.WriteString(fmt.Sprintf("%v", ft.State)) builder.WriteByte(')') return builder.String() diff --git a/entc/integration/gremlin/ent/group.go b/entc/integration/gremlin/ent/group.go index 2194269d80..959555f84a 100644 --- a/entc/integration/gremlin/ent/group.go +++ b/entc/integration/gremlin/ent/group.go @@ -160,18 +160,22 @@ func (gr *Group) Unwrap() *Group { func (gr *Group) String() string { var builder strings.Builder builder.WriteString("Group(") - builder.WriteString(fmt.Sprintf("id=%v", gr.ID)) - builder.WriteString(", active=") + builder.WriteString(fmt.Sprintf("id=%v, ", gr.ID)) + builder.WriteString("active=") builder.WriteString(fmt.Sprintf("%v", gr.Active)) - builder.WriteString(", expire=") + builder.WriteString(", ") + builder.WriteString("expire=") builder.WriteString(gr.Expire.Format(time.ANSIC)) + builder.WriteString(", ") if v := gr.Type; v != nil { - builder.WriteString(", type=") + builder.WriteString("type=") builder.WriteString(*v) } - builder.WriteString(", max_users=") + builder.WriteString(", ") + builder.WriteString("max_users=") builder.WriteString(fmt.Sprintf("%v", gr.MaxUsers)) - builder.WriteString(", name=") + builder.WriteString(", ") + builder.WriteString("name=") builder.WriteString(gr.Name) builder.WriteByte(')') return builder.String() diff --git a/entc/integration/gremlin/ent/groupinfo.go b/entc/integration/gremlin/ent/groupinfo.go index e4d825682a..8ba9b68842 100644 --- a/entc/integration/gremlin/ent/groupinfo.go +++ b/entc/integration/gremlin/ent/groupinfo.go @@ -92,10 +92,11 @@ func (gi *GroupInfo) Unwrap() *GroupInfo { func (gi *GroupInfo) String() string { var builder strings.Builder builder.WriteString("GroupInfo(") - builder.WriteString(fmt.Sprintf("id=%v", gi.ID)) - builder.WriteString(", desc=") + builder.WriteString(fmt.Sprintf("id=%v, ", gi.ID)) + builder.WriteString("desc=") builder.WriteString(gi.Desc) - builder.WriteString(", max_users=") + builder.WriteString(", ") + builder.WriteString("max_users=") builder.WriteString(fmt.Sprintf("%v", gi.MaxUsers)) builder.WriteByte(')') return builder.String() diff --git a/entc/integration/gremlin/ent/item.go b/entc/integration/gremlin/ent/item.go index 9199ff14d1..17eb07cb14 100644 --- a/entc/integration/gremlin/ent/item.go +++ b/entc/integration/gremlin/ent/item.go @@ -62,8 +62,8 @@ func (i *Item) Unwrap() *Item { func (i *Item) String() string { var builder strings.Builder builder.WriteString("Item(") - builder.WriteString(fmt.Sprintf("id=%v", i.ID)) - builder.WriteString(", text=") + builder.WriteString(fmt.Sprintf("id=%v, ", i.ID)) + builder.WriteString("text=") builder.WriteString(i.Text) builder.WriteByte(')') return builder.String() diff --git a/entc/integration/gremlin/ent/node.go b/entc/integration/gremlin/ent/node.go index c71c53a5ff..53f36cd273 100644 --- a/entc/integration/gremlin/ent/node.go +++ b/entc/integration/gremlin/ent/node.go @@ -115,8 +115,8 @@ func (n *Node) Unwrap() *Node { func (n *Node) String() string { var builder strings.Builder builder.WriteString("Node(") - builder.WriteString(fmt.Sprintf("id=%v", n.ID)) - builder.WriteString(", value=") + builder.WriteString(fmt.Sprintf("id=%v, ", n.ID)) + builder.WriteString("value=") builder.WriteString(fmt.Sprintf("%v", n.Value)) builder.WriteByte(')') return builder.String() diff --git a/entc/integration/gremlin/ent/pet.go b/entc/integration/gremlin/ent/pet.go index 6b2d841f6d..0ce9a25614 100644 --- a/entc/integration/gremlin/ent/pet.go +++ b/entc/integration/gremlin/ent/pet.go @@ -128,14 +128,17 @@ func (pe *Pet) Unwrap() *Pet { func (pe *Pet) String() string { var builder strings.Builder builder.WriteString("Pet(") - builder.WriteString(fmt.Sprintf("id=%v", pe.ID)) - builder.WriteString(", age=") + builder.WriteString(fmt.Sprintf("id=%v, ", pe.ID)) + builder.WriteString("age=") builder.WriteString(fmt.Sprintf("%v", pe.Age)) - builder.WriteString(", name=") + builder.WriteString(", ") + builder.WriteString("name=") builder.WriteString(pe.Name) - builder.WriteString(", uuid=") + builder.WriteString(", ") + builder.WriteString("uuid=") builder.WriteString(fmt.Sprintf("%v", pe.UUID)) - builder.WriteString(", nickname=") + builder.WriteString(", ") + builder.WriteString("nickname=") builder.WriteString(pe.Nickname) builder.WriteByte(')') return builder.String() diff --git a/entc/integration/gremlin/ent/task.go b/entc/integration/gremlin/ent/task.go index 3f1e60c2f1..09a95368aa 100644 --- a/entc/integration/gremlin/ent/task.go +++ b/entc/integration/gremlin/ent/task.go @@ -63,8 +63,8 @@ func (t *Task) Unwrap() *Task { func (t *Task) String() string { var builder strings.Builder builder.WriteString("Task(") - builder.WriteString(fmt.Sprintf("id=%v", t.ID)) - builder.WriteString(", priority=") + builder.WriteString(fmt.Sprintf("id=%v, ", t.ID)) + builder.WriteString("priority=") builder.WriteString(fmt.Sprintf("%v", t.Priority)) builder.WriteByte(')') return builder.String() diff --git a/entc/integration/gremlin/ent/user.go b/entc/integration/gremlin/ent/user.go index eee14d5167..baa797b02f 100644 --- a/entc/integration/gremlin/ent/user.go +++ b/entc/integration/gremlin/ent/user.go @@ -311,27 +311,37 @@ func (u *User) Unwrap() *User { func (u *User) String() string { var builder strings.Builder builder.WriteString("User(") - builder.WriteString(fmt.Sprintf("id=%v", u.ID)) - builder.WriteString(", optional_int=") + builder.WriteString(fmt.Sprintf("id=%v, ", u.ID)) + builder.WriteString("optional_int=") builder.WriteString(fmt.Sprintf("%v", u.OptionalInt)) - builder.WriteString(", age=") + builder.WriteString(", ") + builder.WriteString("age=") builder.WriteString(fmt.Sprintf("%v", u.Age)) - builder.WriteString(", name=") + builder.WriteString(", ") + builder.WriteString("name=") builder.WriteString(u.Name) - builder.WriteString(", last=") + builder.WriteString(", ") + builder.WriteString("last=") builder.WriteString(u.Last) - builder.WriteString(", nickname=") + builder.WriteString(", ") + builder.WriteString("nickname=") builder.WriteString(u.Nickname) - builder.WriteString(", address=") + builder.WriteString(", ") + builder.WriteString("address=") builder.WriteString(u.Address) - builder.WriteString(", phone=") + builder.WriteString(", ") + builder.WriteString("phone=") builder.WriteString(u.Phone) - builder.WriteString(", password=") - builder.WriteString(", role=") + builder.WriteString(", ") + builder.WriteString("password=") + builder.WriteString(", ") + builder.WriteString("role=") builder.WriteString(fmt.Sprintf("%v", u.Role)) - builder.WriteString(", employment=") + builder.WriteString(", ") + builder.WriteString("employment=") builder.WriteString(fmt.Sprintf("%v", u.Employment)) - builder.WriteString(", SSOCert=") + builder.WriteString(", ") + builder.WriteString("SSOCert=") builder.WriteString(u.SSOCert) builder.WriteByte(')') return builder.String() diff --git a/entc/integration/hooks/ent/card.go b/entc/integration/hooks/ent/card.go index 62709f62de..76ad6801d8 100644 --- a/entc/integration/hooks/ent/card.go +++ b/entc/integration/hooks/ent/card.go @@ -157,14 +157,17 @@ func (c *Card) Unwrap() *Card { func (c *Card) String() string { var builder strings.Builder builder.WriteString("Card(") - builder.WriteString(fmt.Sprintf("id=%v", c.ID)) - builder.WriteString(", number=") + builder.WriteString(fmt.Sprintf("id=%v, ", c.ID)) + builder.WriteString("number=") builder.WriteString(c.Number) - builder.WriteString(", name=") + builder.WriteString(", ") + builder.WriteString("name=") builder.WriteString(c.Name) - builder.WriteString(", created_at=") + builder.WriteString(", ") + builder.WriteString("created_at=") builder.WriteString(c.CreatedAt.Format(time.ANSIC)) - builder.WriteString(", in_hook=") + builder.WriteString(", ") + builder.WriteString("in_hook=") builder.WriteString(c.InHook) builder.WriteByte(')') return builder.String() diff --git a/entc/integration/hooks/ent/card_create.go b/entc/integration/hooks/ent/card_create.go index 2ace168190..29e352a48b 100644 --- a/entc/integration/hooks/ent/card_create.go +++ b/entc/integration/hooks/ent/card_create.go @@ -324,11 +324,11 @@ func (ccb *CardCreateBulk) Save(ctx context.Context) ([]*Card, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/entc/integration/hooks/ent/client.go b/entc/integration/hooks/ent/client.go index 7e04e3233e..c0543346a8 100644 --- a/entc/integration/hooks/ent/client.go +++ b/entc/integration/hooks/ent/client.go @@ -150,7 +150,7 @@ func (c *CardClient) Use(hooks ...Hook) { c.hooks.Card = append(c.hooks.Card, hooks...) } -// Create returns a create builder for Card. +// Create returns a builder for creating a Card entity. func (c *CardClient) Create() *CardCreate { mutation := newCardMutation(c.config, OpCreate) return &CardCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -185,12 +185,12 @@ func (c *CardClient) Delete() *CardDelete { return &CardDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *CardClient) DeleteOne(ca *Card) *CardDeleteOne { return c.DeleteOneID(ca.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *CardClient) DeleteOneID(id int) *CardDeleteOne { builder := c.Delete().Where(card.ID(id)) builder.mutation.id = &id @@ -257,7 +257,7 @@ func (c *UserClient) Use(hooks ...Hook) { c.hooks.User = append(c.hooks.User, hooks...) } -// Create returns a create builder for User. +// Create returns a builder for creating a User entity. func (c *UserClient) Create() *UserCreate { mutation := newUserMutation(c.config, OpCreate) return &UserCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -292,12 +292,12 @@ func (c *UserClient) Delete() *UserDelete { return &UserDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *UserClient) DeleteOne(u *User) *UserDeleteOne { return c.DeleteOneID(u.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *UserClient) DeleteOneID(id int) *UserDeleteOne { builder := c.Delete().Where(user.ID(id)) builder.mutation.id = &id diff --git a/entc/integration/hooks/ent/user.go b/entc/integration/hooks/ent/user.go index c0e2ebddc7..3957a03588 100644 --- a/entc/integration/hooks/ent/user.go +++ b/entc/integration/hooks/ent/user.go @@ -183,14 +183,17 @@ func (u *User) Unwrap() *User { func (u *User) String() string { var builder strings.Builder builder.WriteString("User(") - builder.WriteString(fmt.Sprintf("id=%v", u.ID)) - builder.WriteString(", version=") + builder.WriteString(fmt.Sprintf("id=%v, ", u.ID)) + builder.WriteString("version=") builder.WriteString(fmt.Sprintf("%v", u.Version)) - builder.WriteString(", name=") + builder.WriteString(", ") + builder.WriteString("name=") builder.WriteString(u.Name) - builder.WriteString(", worth=") + builder.WriteString(", ") + builder.WriteString("worth=") builder.WriteString(fmt.Sprintf("%v", u.Worth)) - builder.WriteString(", password=") + builder.WriteString(", ") + builder.WriteString("password=") builder.WriteByte(')') return builder.String() } diff --git a/entc/integration/hooks/ent/user_create.go b/entc/integration/hooks/ent/user_create.go index ccc1b34405..4ff11fe97b 100644 --- a/entc/integration/hooks/ent/user_create.go +++ b/entc/integration/hooks/ent/user_create.go @@ -376,11 +376,11 @@ func (ucb *UserCreateBulk) Save(ctx context.Context) ([]*User, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/entc/integration/idtype/ent/client.go b/entc/integration/idtype/ent/client.go index 5b39a57a72..9f42229cca 100644 --- a/entc/integration/idtype/ent/client.go +++ b/entc/integration/idtype/ent/client.go @@ -143,7 +143,7 @@ func (c *UserClient) Use(hooks ...Hook) { c.hooks.User = append(c.hooks.User, hooks...) } -// Create returns a create builder for User. +// Create returns a builder for creating a User entity. func (c *UserClient) Create() *UserCreate { mutation := newUserMutation(c.config, OpCreate) return &UserCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -178,12 +178,12 @@ func (c *UserClient) Delete() *UserDelete { return &UserDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *UserClient) DeleteOne(u *User) *UserDeleteOne { return c.DeleteOneID(u.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *UserClient) DeleteOneID(id uint64) *UserDeleteOne { builder := c.Delete().Where(user.ID(id)) builder.mutation.id = &id diff --git a/entc/integration/idtype/ent/user.go b/entc/integration/idtype/ent/user.go index 2a46c95e53..4677c96775 100644 --- a/entc/integration/idtype/ent/user.go +++ b/entc/integration/idtype/ent/user.go @@ -159,8 +159,8 @@ func (u *User) Unwrap() *User { func (u *User) String() string { var builder strings.Builder builder.WriteString("User(") - builder.WriteString(fmt.Sprintf("id=%v", u.ID)) - builder.WriteString(", name=") + builder.WriteString(fmt.Sprintf("id=%v, ", u.ID)) + builder.WriteString("name=") builder.WriteString(u.Name) builder.WriteByte(')') return builder.String() diff --git a/entc/integration/idtype/ent/user_create.go b/entc/integration/idtype/ent/user_create.go index b305d6fb15..0108bc8653 100644 --- a/entc/integration/idtype/ent/user_create.go +++ b/entc/integration/idtype/ent/user_create.go @@ -293,11 +293,11 @@ func (ucb *UserCreateBulk) Save(ctx context.Context) ([]*User, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = uint64(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/entc/integration/json/ent/client.go b/entc/integration/json/ent/client.go index 8f17169df4..aeb77c9b2d 100644 --- a/entc/integration/json/ent/client.go +++ b/entc/integration/json/ent/client.go @@ -142,7 +142,7 @@ func (c *UserClient) Use(hooks ...Hook) { c.hooks.User = append(c.hooks.User, hooks...) } -// Create returns a create builder for User. +// Create returns a builder for creating a User entity. func (c *UserClient) Create() *UserCreate { mutation := newUserMutation(c.config, OpCreate) return &UserCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -177,12 +177,12 @@ func (c *UserClient) Delete() *UserDelete { return &UserDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *UserClient) DeleteOne(u *User) *UserDeleteOne { return c.DeleteOneID(u.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *UserClient) DeleteOneID(id int) *UserDeleteOne { builder := c.Delete().Where(user.ID(id)) builder.mutation.id = &id diff --git a/entc/integration/json/ent/user.go b/entc/integration/json/ent/user.go index b4cb063c2f..fe90502307 100644 --- a/entc/integration/json/ent/user.go +++ b/entc/integration/json/ent/user.go @@ -162,22 +162,29 @@ func (u *User) Unwrap() *User { func (u *User) String() string { var builder strings.Builder builder.WriteString("User(") - builder.WriteString(fmt.Sprintf("id=%v", u.ID)) - builder.WriteString(", t=") + builder.WriteString(fmt.Sprintf("id=%v, ", u.ID)) + builder.WriteString("t=") builder.WriteString(fmt.Sprintf("%v", u.T)) - builder.WriteString(", url=") + builder.WriteString(", ") + builder.WriteString("url=") builder.WriteString(fmt.Sprintf("%v", u.URL)) - builder.WriteString(", raw=") + builder.WriteString(", ") + builder.WriteString("raw=") builder.WriteString(fmt.Sprintf("%v", u.Raw)) - builder.WriteString(", dirs=") + builder.WriteString(", ") + builder.WriteString("dirs=") builder.WriteString(fmt.Sprintf("%v", u.Dirs)) - builder.WriteString(", ints=") + builder.WriteString(", ") + builder.WriteString("ints=") builder.WriteString(fmt.Sprintf("%v", u.Ints)) - builder.WriteString(", floats=") + builder.WriteString(", ") + builder.WriteString("floats=") builder.WriteString(fmt.Sprintf("%v", u.Floats)) - builder.WriteString(", strings=") + builder.WriteString(", ") + builder.WriteString("strings=") builder.WriteString(fmt.Sprintf("%v", u.Strings)) - builder.WriteString(", addr=") + builder.WriteString(", ") + builder.WriteString("addr=") builder.WriteString(fmt.Sprintf("%v", u.Addr)) builder.WriteByte(')') return builder.String() diff --git a/entc/integration/json/ent/user_create.go b/entc/integration/json/ent/user_create.go index 171de31ed0..0b482732c5 100644 --- a/entc/integration/json/ent/user_create.go +++ b/entc/integration/json/ent/user_create.go @@ -310,11 +310,11 @@ func (ucb *UserCreateBulk) Save(ctx context.Context) ([]*User, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/entc/integration/migrate/entv1/car_create.go b/entc/integration/migrate/entv1/car_create.go index db0fcdda69..cc1ee94a0f 100644 --- a/entc/integration/migrate/entv1/car_create.go +++ b/entc/integration/migrate/entv1/car_create.go @@ -208,11 +208,11 @@ func (ccb *CarCreateBulk) Save(ctx context.Context) ([]*Car, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/entc/integration/migrate/entv1/client.go b/entc/integration/migrate/entv1/client.go index 996e3e97e2..3ffeb5c5d0 100644 --- a/entc/integration/migrate/entv1/client.go +++ b/entc/integration/migrate/entv1/client.go @@ -164,7 +164,7 @@ func (c *CarClient) Use(hooks ...Hook) { c.hooks.Car = append(c.hooks.Car, hooks...) } -// Create returns a create builder for Car. +// Create returns a builder for creating a Car entity. func (c *CarClient) Create() *CarCreate { mutation := newCarMutation(c.config, OpCreate) return &CarCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -199,12 +199,12 @@ func (c *CarClient) Delete() *CarDelete { return &CarDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *CarClient) DeleteOne(ca *Car) *CarDeleteOne { return c.DeleteOneID(ca.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *CarClient) DeleteOneID(id int) *CarDeleteOne { builder := c.Delete().Where(car.ID(id)) builder.mutation.id = &id @@ -270,7 +270,7 @@ func (c *ConversionClient) Use(hooks ...Hook) { c.hooks.Conversion = append(c.hooks.Conversion, hooks...) } -// Create returns a create builder for Conversion. +// Create returns a builder for creating a Conversion entity. func (c *ConversionClient) Create() *ConversionCreate { mutation := newConversionMutation(c.config, OpCreate) return &ConversionCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -305,12 +305,12 @@ func (c *ConversionClient) Delete() *ConversionDelete { return &ConversionDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *ConversionClient) DeleteOne(co *Conversion) *ConversionDeleteOne { return c.DeleteOneID(co.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *ConversionClient) DeleteOneID(id int) *ConversionDeleteOne { builder := c.Delete().Where(conversion.ID(id)) builder.mutation.id = &id @@ -360,7 +360,7 @@ func (c *CustomTypeClient) Use(hooks ...Hook) { c.hooks.CustomType = append(c.hooks.CustomType, hooks...) } -// Create returns a create builder for CustomType. +// Create returns a builder for creating a CustomType entity. func (c *CustomTypeClient) Create() *CustomTypeCreate { mutation := newCustomTypeMutation(c.config, OpCreate) return &CustomTypeCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -395,12 +395,12 @@ func (c *CustomTypeClient) Delete() *CustomTypeDelete { return &CustomTypeDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *CustomTypeClient) DeleteOne(ct *CustomType) *CustomTypeDeleteOne { return c.DeleteOneID(ct.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *CustomTypeClient) DeleteOneID(id int) *CustomTypeDeleteOne { builder := c.Delete().Where(customtype.ID(id)) builder.mutation.id = &id @@ -450,7 +450,7 @@ func (c *UserClient) Use(hooks ...Hook) { c.hooks.User = append(c.hooks.User, hooks...) } -// Create returns a create builder for User. +// Create returns a builder for creating a User entity. func (c *UserClient) Create() *UserCreate { mutation := newUserMutation(c.config, OpCreate) return &UserCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -485,12 +485,12 @@ func (c *UserClient) Delete() *UserDelete { return &UserDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *UserClient) DeleteOne(u *User) *UserDeleteOne { return c.DeleteOneID(u.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *UserClient) DeleteOneID(id int) *UserDeleteOne { builder := c.Delete().Where(user.ID(id)) builder.mutation.id = &id diff --git a/entc/integration/migrate/entv1/conversion.go b/entc/integration/migrate/entv1/conversion.go index dbb252a739..bcd603ddbc 100644 --- a/entc/integration/migrate/entv1/conversion.go +++ b/entc/integration/migrate/entv1/conversion.go @@ -150,24 +150,32 @@ func (c *Conversion) Unwrap() *Conversion { func (c *Conversion) String() string { var builder strings.Builder builder.WriteString("Conversion(") - builder.WriteString(fmt.Sprintf("id=%v", c.ID)) - builder.WriteString(", name=") + builder.WriteString(fmt.Sprintf("id=%v, ", c.ID)) + builder.WriteString("name=") builder.WriteString(c.Name) - builder.WriteString(", int8_to_string=") + builder.WriteString(", ") + builder.WriteString("int8_to_string=") builder.WriteString(fmt.Sprintf("%v", c.Int8ToString)) - builder.WriteString(", uint8_to_string=") + builder.WriteString(", ") + builder.WriteString("uint8_to_string=") builder.WriteString(fmt.Sprintf("%v", c.Uint8ToString)) - builder.WriteString(", int16_to_string=") + builder.WriteString(", ") + builder.WriteString("int16_to_string=") builder.WriteString(fmt.Sprintf("%v", c.Int16ToString)) - builder.WriteString(", uint16_to_string=") + builder.WriteString(", ") + builder.WriteString("uint16_to_string=") builder.WriteString(fmt.Sprintf("%v", c.Uint16ToString)) - builder.WriteString(", int32_to_string=") + builder.WriteString(", ") + builder.WriteString("int32_to_string=") builder.WriteString(fmt.Sprintf("%v", c.Int32ToString)) - builder.WriteString(", uint32_to_string=") + builder.WriteString(", ") + builder.WriteString("uint32_to_string=") builder.WriteString(fmt.Sprintf("%v", c.Uint32ToString)) - builder.WriteString(", int64_to_string=") + builder.WriteString(", ") + builder.WriteString("int64_to_string=") builder.WriteString(fmt.Sprintf("%v", c.Int64ToString)) - builder.WriteString(", uint64_to_string=") + builder.WriteString(", ") + builder.WriteString("uint64_to_string=") builder.WriteString(fmt.Sprintf("%v", c.Uint64ToString)) builder.WriteByte(')') return builder.String() diff --git a/entc/integration/migrate/entv1/conversion_create.go b/entc/integration/migrate/entv1/conversion_create.go index f815eb89ec..e97afb804b 100644 --- a/entc/integration/migrate/entv1/conversion_create.go +++ b/entc/integration/migrate/entv1/conversion_create.go @@ -366,11 +366,11 @@ func (ccb *ConversionCreateBulk) Save(ctx context.Context) ([]*Conversion, error return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/entc/integration/migrate/entv1/customtype.go b/entc/integration/migrate/entv1/customtype.go index 1394184ce7..9db4b141ae 100644 --- a/entc/integration/migrate/entv1/customtype.go +++ b/entc/integration/migrate/entv1/customtype.go @@ -86,8 +86,8 @@ func (ct *CustomType) Unwrap() *CustomType { func (ct *CustomType) String() string { var builder strings.Builder builder.WriteString("CustomType(") - builder.WriteString(fmt.Sprintf("id=%v", ct.ID)) - builder.WriteString(", custom=") + builder.WriteString(fmt.Sprintf("id=%v, ", ct.ID)) + builder.WriteString("custom=") builder.WriteString(ct.Custom) builder.WriteByte(')') return builder.String() diff --git a/entc/integration/migrate/entv1/customtype_create.go b/entc/integration/migrate/entv1/customtype_create.go index b22d1e33ae..d5a3cfc320 100644 --- a/entc/integration/migrate/entv1/customtype_create.go +++ b/entc/integration/migrate/entv1/customtype_create.go @@ -190,11 +190,11 @@ func (ctcb *CustomTypeCreateBulk) Save(ctx context.Context) ([]*CustomType, erro return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/entc/integration/migrate/entv1/user.go b/entc/integration/migrate/entv1/user.go index 462f03ed8d..8189696ddc 100644 --- a/entc/integration/migrate/entv1/user.go +++ b/entc/integration/migrate/entv1/user.go @@ -286,30 +286,41 @@ func (u *User) Unwrap() *User { func (u *User) String() string { var builder strings.Builder builder.WriteString("User(") - builder.WriteString(fmt.Sprintf("id=%v", u.ID)) - builder.WriteString(", age=") + builder.WriteString(fmt.Sprintf("id=%v, ", u.ID)) + builder.WriteString("age=") builder.WriteString(fmt.Sprintf("%v", u.Age)) - builder.WriteString(", name=") + builder.WriteString(", ") + builder.WriteString("name=") builder.WriteString(u.Name) - builder.WriteString(", description=") + builder.WriteString(", ") + builder.WriteString("description=") builder.WriteString(u.Description) - builder.WriteString(", nickname=") + builder.WriteString(", ") + builder.WriteString("nickname=") builder.WriteString(u.Nickname) - builder.WriteString(", address=") + builder.WriteString(", ") + builder.WriteString("address=") builder.WriteString(u.Address) - builder.WriteString(", renamed=") + builder.WriteString(", ") + builder.WriteString("renamed=") builder.WriteString(u.Renamed) - builder.WriteString(", old_token=") + builder.WriteString(", ") + builder.WriteString("old_token=") builder.WriteString(u.OldToken) - builder.WriteString(", blob=") + builder.WriteString(", ") + builder.WriteString("blob=") builder.WriteString(fmt.Sprintf("%v", u.Blob)) - builder.WriteString(", state=") + builder.WriteString(", ") + builder.WriteString("state=") builder.WriteString(fmt.Sprintf("%v", u.State)) - builder.WriteString(", status=") + builder.WriteString(", ") + builder.WriteString("status=") builder.WriteString(u.Status) - builder.WriteString(", workplace=") + builder.WriteString(", ") + builder.WriteString("workplace=") builder.WriteString(u.Workplace) - builder.WriteString(", drop_optional=") + builder.WriteString(", ") + builder.WriteString("drop_optional=") builder.WriteString(u.DropOptional) builder.WriteByte(')') return builder.String() diff --git a/entc/integration/migrate/entv1/user_create.go b/entc/integration/migrate/entv1/user_create.go index 7cc5771f5c..808c7df6f0 100644 --- a/entc/integration/migrate/entv1/user_create.go +++ b/entc/integration/migrate/entv1/user_create.go @@ -610,11 +610,11 @@ func (ucb *UserCreateBulk) Save(ctx context.Context) ([]*User, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil && nodes[i].ID == 0 { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/entc/integration/migrate/entv2/car.go b/entc/integration/migrate/entv2/car.go index d34c482161..605b5a60c0 100644 --- a/entc/integration/migrate/entv2/car.go +++ b/entc/integration/migrate/entv2/car.go @@ -128,8 +128,8 @@ func (c *Car) Unwrap() *Car { func (c *Car) String() string { var builder strings.Builder builder.WriteString("Car(") - builder.WriteString(fmt.Sprintf("id=%v", c.ID)) - builder.WriteString(", name=") + builder.WriteString(fmt.Sprintf("id=%v, ", c.ID)) + builder.WriteString("name=") builder.WriteString(c.Name) builder.WriteByte(')') return builder.String() diff --git a/entc/integration/migrate/entv2/car_create.go b/entc/integration/migrate/entv2/car_create.go index eaf99f4f59..f79cce7843 100644 --- a/entc/integration/migrate/entv2/car_create.go +++ b/entc/integration/migrate/entv2/car_create.go @@ -226,11 +226,11 @@ func (ccb *CarCreateBulk) Save(ctx context.Context) ([]*Car, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/entc/integration/migrate/entv2/client.go b/entc/integration/migrate/entv2/client.go index 7fbb088592..569bdfd469 100644 --- a/entc/integration/migrate/entv2/client.go +++ b/entc/integration/migrate/entv2/client.go @@ -185,7 +185,7 @@ func (c *CarClient) Use(hooks ...Hook) { c.hooks.Car = append(c.hooks.Car, hooks...) } -// Create returns a create builder for Car. +// Create returns a builder for creating a Car entity. func (c *CarClient) Create() *CarCreate { mutation := newCarMutation(c.config, OpCreate) return &CarCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -220,12 +220,12 @@ func (c *CarClient) Delete() *CarDelete { return &CarDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *CarClient) DeleteOne(ca *Car) *CarDeleteOne { return c.DeleteOneID(ca.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *CarClient) DeleteOneID(id int) *CarDeleteOne { builder := c.Delete().Where(car.ID(id)) builder.mutation.id = &id @@ -291,7 +291,7 @@ func (c *ConversionClient) Use(hooks ...Hook) { c.hooks.Conversion = append(c.hooks.Conversion, hooks...) } -// Create returns a create builder for Conversion. +// Create returns a builder for creating a Conversion entity. func (c *ConversionClient) Create() *ConversionCreate { mutation := newConversionMutation(c.config, OpCreate) return &ConversionCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -326,12 +326,12 @@ func (c *ConversionClient) Delete() *ConversionDelete { return &ConversionDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *ConversionClient) DeleteOne(co *Conversion) *ConversionDeleteOne { return c.DeleteOneID(co.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *ConversionClient) DeleteOneID(id int) *ConversionDeleteOne { builder := c.Delete().Where(conversion.ID(id)) builder.mutation.id = &id @@ -381,7 +381,7 @@ func (c *CustomTypeClient) Use(hooks ...Hook) { c.hooks.CustomType = append(c.hooks.CustomType, hooks...) } -// Create returns a create builder for CustomType. +// Create returns a builder for creating a CustomType entity. func (c *CustomTypeClient) Create() *CustomTypeCreate { mutation := newCustomTypeMutation(c.config, OpCreate) return &CustomTypeCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -416,12 +416,12 @@ func (c *CustomTypeClient) Delete() *CustomTypeDelete { return &CustomTypeDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *CustomTypeClient) DeleteOne(ct *CustomType) *CustomTypeDeleteOne { return c.DeleteOneID(ct.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *CustomTypeClient) DeleteOneID(id int) *CustomTypeDeleteOne { builder := c.Delete().Where(customtype.ID(id)) builder.mutation.id = &id @@ -471,7 +471,7 @@ func (c *GroupClient) Use(hooks ...Hook) { c.hooks.Group = append(c.hooks.Group, hooks...) } -// Create returns a create builder for Group. +// Create returns a builder for creating a Group entity. func (c *GroupClient) Create() *GroupCreate { mutation := newGroupMutation(c.config, OpCreate) return &GroupCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -506,12 +506,12 @@ func (c *GroupClient) Delete() *GroupDelete { return &GroupDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *GroupClient) DeleteOne(gr *Group) *GroupDeleteOne { return c.DeleteOneID(gr.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *GroupClient) DeleteOneID(id int) *GroupDeleteOne { builder := c.Delete().Where(group.ID(id)) builder.mutation.id = &id @@ -561,7 +561,7 @@ func (c *MediaClient) Use(hooks ...Hook) { c.hooks.Media = append(c.hooks.Media, hooks...) } -// Create returns a create builder for Media. +// Create returns a builder for creating a Media entity. func (c *MediaClient) Create() *MediaCreate { mutation := newMediaMutation(c.config, OpCreate) return &MediaCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -596,12 +596,12 @@ func (c *MediaClient) Delete() *MediaDelete { return &MediaDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *MediaClient) DeleteOne(m *Media) *MediaDeleteOne { return c.DeleteOneID(m.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *MediaClient) DeleteOneID(id int) *MediaDeleteOne { builder := c.Delete().Where(media.ID(id)) builder.mutation.id = &id @@ -651,7 +651,7 @@ func (c *PetClient) Use(hooks ...Hook) { c.hooks.Pet = append(c.hooks.Pet, hooks...) } -// Create returns a create builder for Pet. +// Create returns a builder for creating a Pet entity. func (c *PetClient) Create() *PetCreate { mutation := newPetMutation(c.config, OpCreate) return &PetCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -686,12 +686,12 @@ func (c *PetClient) Delete() *PetDelete { return &PetDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *PetClient) DeleteOne(pe *Pet) *PetDeleteOne { return c.DeleteOneID(pe.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *PetClient) DeleteOneID(id int) *PetDeleteOne { builder := c.Delete().Where(pet.ID(id)) builder.mutation.id = &id @@ -757,7 +757,7 @@ func (c *UserClient) Use(hooks ...Hook) { c.hooks.User = append(c.hooks.User, hooks...) } -// Create returns a create builder for User. +// Create returns a builder for creating a User entity. func (c *UserClient) Create() *UserCreate { mutation := newUserMutation(c.config, OpCreate) return &UserCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -792,12 +792,12 @@ func (c *UserClient) Delete() *UserDelete { return &UserDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *UserClient) DeleteOne(u *User) *UserDeleteOne { return c.DeleteOneID(u.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *UserClient) DeleteOneID(id int) *UserDeleteOne { builder := c.Delete().Where(user.ID(id)) builder.mutation.id = &id diff --git a/entc/integration/migrate/entv2/conversion.go b/entc/integration/migrate/entv2/conversion.go index 434022f123..298b6dcecc 100644 --- a/entc/integration/migrate/entv2/conversion.go +++ b/entc/integration/migrate/entv2/conversion.go @@ -150,24 +150,32 @@ func (c *Conversion) Unwrap() *Conversion { func (c *Conversion) String() string { var builder strings.Builder builder.WriteString("Conversion(") - builder.WriteString(fmt.Sprintf("id=%v", c.ID)) - builder.WriteString(", name=") + builder.WriteString(fmt.Sprintf("id=%v, ", c.ID)) + builder.WriteString("name=") builder.WriteString(c.Name) - builder.WriteString(", int8_to_string=") + builder.WriteString(", ") + builder.WriteString("int8_to_string=") builder.WriteString(c.Int8ToString) - builder.WriteString(", uint8_to_string=") + builder.WriteString(", ") + builder.WriteString("uint8_to_string=") builder.WriteString(c.Uint8ToString) - builder.WriteString(", int16_to_string=") + builder.WriteString(", ") + builder.WriteString("int16_to_string=") builder.WriteString(c.Int16ToString) - builder.WriteString(", uint16_to_string=") + builder.WriteString(", ") + builder.WriteString("uint16_to_string=") builder.WriteString(c.Uint16ToString) - builder.WriteString(", int32_to_string=") + builder.WriteString(", ") + builder.WriteString("int32_to_string=") builder.WriteString(c.Int32ToString) - builder.WriteString(", uint32_to_string=") + builder.WriteString(", ") + builder.WriteString("uint32_to_string=") builder.WriteString(c.Uint32ToString) - builder.WriteString(", int64_to_string=") + builder.WriteString(", ") + builder.WriteString("int64_to_string=") builder.WriteString(c.Int64ToString) - builder.WriteString(", uint64_to_string=") + builder.WriteString(", ") + builder.WriteString("uint64_to_string=") builder.WriteString(c.Uint64ToString) builder.WriteByte(')') return builder.String() diff --git a/entc/integration/migrate/entv2/conversion_create.go b/entc/integration/migrate/entv2/conversion_create.go index 66abbf649d..a8d19a2837 100644 --- a/entc/integration/migrate/entv2/conversion_create.go +++ b/entc/integration/migrate/entv2/conversion_create.go @@ -366,11 +366,11 @@ func (ccb *ConversionCreateBulk) Save(ctx context.Context) ([]*Conversion, error return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/entc/integration/migrate/entv2/customtype.go b/entc/integration/migrate/entv2/customtype.go index 7b6b0e1c98..6b0ff3d519 100644 --- a/entc/integration/migrate/entv2/customtype.go +++ b/entc/integration/migrate/entv2/customtype.go @@ -105,12 +105,14 @@ func (ct *CustomType) Unwrap() *CustomType { func (ct *CustomType) String() string { var builder strings.Builder builder.WriteString("CustomType(") - builder.WriteString(fmt.Sprintf("id=%v", ct.ID)) - builder.WriteString(", custom=") + builder.WriteString(fmt.Sprintf("id=%v, ", ct.ID)) + builder.WriteString("custom=") builder.WriteString(ct.Custom) - builder.WriteString(", tz0=") + builder.WriteString(", ") + builder.WriteString("tz0=") builder.WriteString(ct.Tz0.Format(time.ANSIC)) - builder.WriteString(", tz3=") + builder.WriteString(", ") + builder.WriteString("tz3=") builder.WriteString(ct.Tz3.Format(time.ANSIC)) builder.WriteByte(')') return builder.String() diff --git a/entc/integration/migrate/entv2/customtype_create.go b/entc/integration/migrate/entv2/customtype_create.go index 1ce2a03ebd..c6613fe8f6 100644 --- a/entc/integration/migrate/entv2/customtype_create.go +++ b/entc/integration/migrate/entv2/customtype_create.go @@ -235,11 +235,11 @@ func (ctcb *CustomTypeCreateBulk) Save(ctx context.Context) ([]*CustomType, erro return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/entc/integration/migrate/entv2/group_create.go b/entc/integration/migrate/entv2/group_create.go index ed82cd8c0f..b50cb1d68d 100644 --- a/entc/integration/migrate/entv2/group_create.go +++ b/entc/integration/migrate/entv2/group_create.go @@ -168,11 +168,11 @@ func (gcb *GroupCreateBulk) Save(ctx context.Context) ([]*Group, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/entc/integration/migrate/entv2/media.go b/entc/integration/migrate/entv2/media.go index 748dd41103..f364472e2e 100644 --- a/entc/integration/migrate/entv2/media.go +++ b/entc/integration/migrate/entv2/media.go @@ -102,12 +102,14 @@ func (m *Media) Unwrap() *Media { func (m *Media) String() string { var builder strings.Builder builder.WriteString("Media(") - builder.WriteString(fmt.Sprintf("id=%v", m.ID)) - builder.WriteString(", source=") + builder.WriteString(fmt.Sprintf("id=%v, ", m.ID)) + builder.WriteString("source=") builder.WriteString(m.Source) - builder.WriteString(", source_uri=") + builder.WriteString(", ") + builder.WriteString("source_uri=") builder.WriteString(m.SourceURI) - builder.WriteString(", text=") + builder.WriteString(", ") + builder.WriteString("text=") builder.WriteString(m.Text) builder.WriteByte(')') return builder.String() diff --git a/entc/integration/migrate/entv2/media_create.go b/entc/integration/migrate/entv2/media_create.go index e59e10a316..1437a3d542 100644 --- a/entc/integration/migrate/entv2/media_create.go +++ b/entc/integration/migrate/entv2/media_create.go @@ -234,11 +234,11 @@ func (mcb *MediaCreateBulk) Save(ctx context.Context) ([]*Media, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/entc/integration/migrate/entv2/pet.go b/entc/integration/migrate/entv2/pet.go index 7269625f39..0f180ac77b 100644 --- a/entc/integration/migrate/entv2/pet.go +++ b/entc/integration/migrate/entv2/pet.go @@ -128,8 +128,8 @@ func (pe *Pet) Unwrap() *Pet { func (pe *Pet) String() string { var builder strings.Builder builder.WriteString("Pet(") - builder.WriteString(fmt.Sprintf("id=%v", pe.ID)) - builder.WriteString(", name=") + builder.WriteString(fmt.Sprintf("id=%v, ", pe.ID)) + builder.WriteString("name=") builder.WriteString(pe.Name) builder.WriteByte(')') return builder.String() diff --git a/entc/integration/migrate/entv2/pet_create.go b/entc/integration/migrate/entv2/pet_create.go index 4a008c0bd6..05c62a43ab 100644 --- a/entc/integration/migrate/entv2/pet_create.go +++ b/entc/integration/migrate/entv2/pet_create.go @@ -230,11 +230,11 @@ func (pcb *PetCreateBulk) Save(ctx context.Context) ([]*Pet, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/entc/integration/migrate/entv2/user.go b/entc/integration/migrate/entv2/user.go index 1f54cd96b5..85efd972bd 100644 --- a/entc/integration/migrate/entv2/user.go +++ b/entc/integration/migrate/entv2/user.go @@ -283,40 +283,56 @@ func (u *User) Unwrap() *User { func (u *User) String() string { var builder strings.Builder builder.WriteString("User(") - builder.WriteString(fmt.Sprintf("id=%v", u.ID)) - builder.WriteString(", mixed_string=") + builder.WriteString(fmt.Sprintf("id=%v, ", u.ID)) + builder.WriteString("mixed_string=") builder.WriteString(u.MixedString) - builder.WriteString(", mixed_enum=") + builder.WriteString(", ") + builder.WriteString("mixed_enum=") builder.WriteString(fmt.Sprintf("%v", u.MixedEnum)) - builder.WriteString(", age=") + builder.WriteString(", ") + builder.WriteString("age=") builder.WriteString(fmt.Sprintf("%v", u.Age)) - builder.WriteString(", name=") + builder.WriteString(", ") + builder.WriteString("name=") builder.WriteString(u.Name) - builder.WriteString(", description=") + builder.WriteString(", ") + builder.WriteString("description=") builder.WriteString(u.Description) - builder.WriteString(", nickname=") + builder.WriteString(", ") + builder.WriteString("nickname=") builder.WriteString(u.Nickname) - builder.WriteString(", phone=") + builder.WriteString(", ") + builder.WriteString("phone=") builder.WriteString(u.Phone) - builder.WriteString(", buffer=") + builder.WriteString(", ") + builder.WriteString("buffer=") builder.WriteString(fmt.Sprintf("%v", u.Buffer)) - builder.WriteString(", title=") + builder.WriteString(", ") + builder.WriteString("title=") builder.WriteString(u.Title) - builder.WriteString(", new_name=") + builder.WriteString(", ") + builder.WriteString("new_name=") builder.WriteString(u.NewName) - builder.WriteString(", new_token=") + builder.WriteString(", ") + builder.WriteString("new_token=") builder.WriteString(u.NewToken) - builder.WriteString(", blob=") + builder.WriteString(", ") + builder.WriteString("blob=") builder.WriteString(fmt.Sprintf("%v", u.Blob)) - builder.WriteString(", state=") + builder.WriteString(", ") + builder.WriteString("state=") builder.WriteString(fmt.Sprintf("%v", u.State)) - builder.WriteString(", status=") + builder.WriteString(", ") + builder.WriteString("status=") builder.WriteString(fmt.Sprintf("%v", u.Status)) - builder.WriteString(", workplace=") + builder.WriteString(", ") + builder.WriteString("workplace=") builder.WriteString(u.Workplace) - builder.WriteString(", created_at=") + builder.WriteString(", ") + builder.WriteString("created_at=") builder.WriteString(u.CreatedAt.Format(time.ANSIC)) - builder.WriteString(", drop_optional=") + builder.WriteString(", ") + builder.WriteString("drop_optional=") builder.WriteString(u.DropOptional) builder.WriteByte(')') return builder.String() diff --git a/entc/integration/migrate/entv2/user_create.go b/entc/integration/migrate/entv2/user_create.go index 75a24aa6f1..ef5163ea2a 100644 --- a/entc/integration/migrate/entv2/user_create.go +++ b/entc/integration/migrate/entv2/user_create.go @@ -721,11 +721,11 @@ func (ucb *UserCreateBulk) Save(ctx context.Context) ([]*User, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil && nodes[i].ID == 0 { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/entc/integration/migrate/versioned/client.go b/entc/integration/migrate/versioned/client.go index 826489b83c..fc373543c9 100644 --- a/entc/integration/migrate/versioned/client.go +++ b/entc/integration/migrate/versioned/client.go @@ -142,7 +142,7 @@ func (c *UserClient) Use(hooks ...Hook) { c.hooks.User = append(c.hooks.User, hooks...) } -// Create returns a create builder for User. +// Create returns a builder for creating a User entity. func (c *UserClient) Create() *UserCreate { mutation := newUserMutation(c.config, OpCreate) return &UserCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -177,12 +177,12 @@ func (c *UserClient) Delete() *UserDelete { return &UserDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *UserClient) DeleteOne(u *User) *UserDeleteOne { return c.DeleteOneID(u.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *UserClient) DeleteOneID(id int) *UserDeleteOne { builder := c.Delete().Where(user.ID(id)) builder.mutation.id = &id diff --git a/entc/integration/migrate/versioned/user.go b/entc/integration/migrate/versioned/user.go index 951951b010..7faf3dfc20 100644 --- a/entc/integration/migrate/versioned/user.go +++ b/entc/integration/migrate/versioned/user.go @@ -110,14 +110,17 @@ func (u *User) Unwrap() *User { func (u *User) String() string { var builder strings.Builder builder.WriteString("User(") - builder.WriteString(fmt.Sprintf("id=%v", u.ID)) - builder.WriteString(", age=") + builder.WriteString(fmt.Sprintf("id=%v, ", u.ID)) + builder.WriteString("age=") builder.WriteString(fmt.Sprintf("%v", u.Age)) - builder.WriteString(", name=") + builder.WriteString(", ") + builder.WriteString("name=") builder.WriteString(u.Name) - builder.WriteString(", description=") + builder.WriteString(", ") + builder.WriteString("description=") builder.WriteString(u.Description) - builder.WriteString(", address=") + builder.WriteString(", ") + builder.WriteString("address=") builder.WriteString(u.Address) builder.WriteByte(')') return builder.String() diff --git a/entc/integration/migrate/versioned/user_create.go b/entc/integration/migrate/versioned/user_create.go index b0ac225b8d..0c38a50d09 100644 --- a/entc/integration/migrate/versioned/user_create.go +++ b/entc/integration/migrate/versioned/user_create.go @@ -264,11 +264,11 @@ func (ucb *UserCreateBulk) Save(ctx context.Context) ([]*User, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil && nodes[i].ID == 0 { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/entc/integration/multischema/ent/client.go b/entc/integration/multischema/ent/client.go index c560dad402..f99a429f07 100644 --- a/entc/integration/multischema/ent/client.go +++ b/entc/integration/multischema/ent/client.go @@ -157,7 +157,7 @@ func (c *GroupClient) Use(hooks ...Hook) { c.hooks.Group = append(c.hooks.Group, hooks...) } -// Create returns a create builder for Group. +// Create returns a builder for creating a Group entity. func (c *GroupClient) Create() *GroupCreate { mutation := newGroupMutation(c.config, OpCreate) return &GroupCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -192,12 +192,12 @@ func (c *GroupClient) Delete() *GroupDelete { return &GroupDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *GroupClient) DeleteOne(gr *Group) *GroupDeleteOne { return c.DeleteOneID(gr.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *GroupClient) DeleteOneID(id int) *GroupDeleteOne { builder := c.Delete().Where(group.ID(id)) builder.mutation.id = &id @@ -266,7 +266,7 @@ func (c *PetClient) Use(hooks ...Hook) { c.hooks.Pet = append(c.hooks.Pet, hooks...) } -// Create returns a create builder for Pet. +// Create returns a builder for creating a Pet entity. func (c *PetClient) Create() *PetCreate { mutation := newPetMutation(c.config, OpCreate) return &PetCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -301,12 +301,12 @@ func (c *PetClient) Delete() *PetDelete { return &PetDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *PetClient) DeleteOne(pe *Pet) *PetDeleteOne { return c.DeleteOneID(pe.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *PetClient) DeleteOneID(id int) *PetDeleteOne { builder := c.Delete().Where(pet.ID(id)) builder.mutation.id = &id @@ -375,7 +375,7 @@ func (c *UserClient) Use(hooks ...Hook) { c.hooks.User = append(c.hooks.User, hooks...) } -// Create returns a create builder for User. +// Create returns a builder for creating a User entity. func (c *UserClient) Create() *UserCreate { mutation := newUserMutation(c.config, OpCreate) return &UserCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -410,12 +410,12 @@ func (c *UserClient) Delete() *UserDelete { return &UserDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *UserClient) DeleteOne(u *User) *UserDeleteOne { return c.DeleteOneID(u.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *UserClient) DeleteOneID(id int) *UserDeleteOne { builder := c.Delete().Where(user.ID(id)) builder.mutation.id = &id diff --git a/entc/integration/multischema/ent/group.go b/entc/integration/multischema/ent/group.go index 55f45f4213..871d727ee1 100644 --- a/entc/integration/multischema/ent/group.go +++ b/entc/integration/multischema/ent/group.go @@ -112,8 +112,8 @@ func (gr *Group) Unwrap() *Group { func (gr *Group) String() string { var builder strings.Builder builder.WriteString("Group(") - builder.WriteString(fmt.Sprintf("id=%v", gr.ID)) - builder.WriteString(", name=") + builder.WriteString(fmt.Sprintf("id=%v, ", gr.ID)) + builder.WriteString("name=") builder.WriteString(gr.Name) builder.WriteByte(')') return builder.String() diff --git a/entc/integration/multischema/ent/group_create.go b/entc/integration/multischema/ent/group_create.go index 47134d1701..73074e57dc 100644 --- a/entc/integration/multischema/ent/group_create.go +++ b/entc/integration/multischema/ent/group_create.go @@ -241,11 +241,11 @@ func (gcb *GroupCreateBulk) Save(ctx context.Context) ([]*Group, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/entc/integration/multischema/ent/pet.go b/entc/integration/multischema/ent/pet.go index 052c52523c..a2d591cbe9 100644 --- a/entc/integration/multischema/ent/pet.go +++ b/entc/integration/multischema/ent/pet.go @@ -126,10 +126,11 @@ func (pe *Pet) Unwrap() *Pet { func (pe *Pet) String() string { var builder strings.Builder builder.WriteString("Pet(") - builder.WriteString(fmt.Sprintf("id=%v", pe.ID)) - builder.WriteString(", name=") + builder.WriteString(fmt.Sprintf("id=%v, ", pe.ID)) + builder.WriteString("name=") builder.WriteString(pe.Name) - builder.WriteString(", owner_id=") + builder.WriteString(", ") + builder.WriteString("owner_id=") builder.WriteString(fmt.Sprintf("%v", pe.OwnerID)) builder.WriteByte(')') return builder.String() diff --git a/entc/integration/multischema/ent/pet_create.go b/entc/integration/multischema/ent/pet_create.go index cb38a47943..fe7b50d4ec 100644 --- a/entc/integration/multischema/ent/pet_create.go +++ b/entc/integration/multischema/ent/pet_create.go @@ -246,11 +246,11 @@ func (pcb *PetCreateBulk) Save(ctx context.Context) ([]*Pet, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/entc/integration/multischema/ent/user.go b/entc/integration/multischema/ent/user.go index fdf80b84d7..fe25d3ad72 100644 --- a/entc/integration/multischema/ent/user.go +++ b/entc/integration/multischema/ent/user.go @@ -128,8 +128,8 @@ func (u *User) Unwrap() *User { func (u *User) String() string { var builder strings.Builder builder.WriteString("User(") - builder.WriteString(fmt.Sprintf("id=%v", u.ID)) - builder.WriteString(", name=") + builder.WriteString(fmt.Sprintf("id=%v, ", u.ID)) + builder.WriteString("name=") builder.WriteString(u.Name) builder.WriteByte(')') return builder.String() diff --git a/entc/integration/multischema/ent/user_create.go b/entc/integration/multischema/ent/user_create.go index 09431a64f7..0c1539a18b 100644 --- a/entc/integration/multischema/ent/user_create.go +++ b/entc/integration/multischema/ent/user_create.go @@ -277,11 +277,11 @@ func (ucb *UserCreateBulk) Save(ctx context.Context) ([]*User, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/entc/integration/privacy/ent/client.go b/entc/integration/privacy/ent/client.go index e5eb17dd03..4acb0fd8f1 100644 --- a/entc/integration/privacy/ent/client.go +++ b/entc/integration/privacy/ent/client.go @@ -157,7 +157,7 @@ func (c *TaskClient) Use(hooks ...Hook) { c.hooks.Task = append(c.hooks.Task, hooks...) } -// Create returns a create builder for Task. +// Create returns a builder for creating a Task entity. func (c *TaskClient) Create() *TaskCreate { mutation := newTaskMutation(c.config, OpCreate) return &TaskCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -192,12 +192,12 @@ func (c *TaskClient) Delete() *TaskDelete { return &TaskDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *TaskClient) DeleteOne(t *Task) *TaskDeleteOne { return c.DeleteOneID(t.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *TaskClient) DeleteOneID(id int) *TaskDeleteOne { builder := c.Delete().Where(task.ID(id)) builder.mutation.id = &id @@ -280,7 +280,7 @@ func (c *TeamClient) Use(hooks ...Hook) { c.hooks.Team = append(c.hooks.Team, hooks...) } -// Create returns a create builder for Team. +// Create returns a builder for creating a Team entity. func (c *TeamClient) Create() *TeamCreate { mutation := newTeamMutation(c.config, OpCreate) return &TeamCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -315,12 +315,12 @@ func (c *TeamClient) Delete() *TeamDelete { return &TeamDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *TeamClient) DeleteOne(t *Team) *TeamDeleteOne { return c.DeleteOneID(t.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *TeamClient) DeleteOneID(id int) *TeamDeleteOne { builder := c.Delete().Where(team.ID(id)) builder.mutation.id = &id @@ -403,7 +403,7 @@ func (c *UserClient) Use(hooks ...Hook) { c.hooks.User = append(c.hooks.User, hooks...) } -// Create returns a create builder for User. +// Create returns a builder for creating a User entity. func (c *UserClient) Create() *UserCreate { mutation := newUserMutation(c.config, OpCreate) return &UserCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -438,12 +438,12 @@ func (c *UserClient) Delete() *UserDelete { return &UserDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *UserClient) DeleteOne(u *User) *UserDeleteOne { return c.DeleteOneID(u.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *UserClient) DeleteOneID(id int) *UserDeleteOne { builder := c.Delete().Where(user.ID(id)) builder.mutation.id = &id diff --git a/entc/integration/privacy/ent/task.go b/entc/integration/privacy/ent/task.go index edbc0e24bf..b2d35ac474 100644 --- a/entc/integration/privacy/ent/task.go +++ b/entc/integration/privacy/ent/task.go @@ -171,14 +171,17 @@ func (t *Task) Unwrap() *Task { func (t *Task) String() string { var builder strings.Builder builder.WriteString("Task(") - builder.WriteString(fmt.Sprintf("id=%v", t.ID)) - builder.WriteString(", title=") + builder.WriteString(fmt.Sprintf("id=%v, ", t.ID)) + builder.WriteString("title=") builder.WriteString(t.Title) - builder.WriteString(", description=") + builder.WriteString(", ") + builder.WriteString("description=") builder.WriteString(t.Description) - builder.WriteString(", status=") + builder.WriteString(", ") + builder.WriteString("status=") builder.WriteString(fmt.Sprintf("%v", t.Status)) - builder.WriteString(", uuid=") + builder.WriteString(", ") + builder.WriteString("uuid=") builder.WriteString(fmt.Sprintf("%v", t.UUID)) builder.WriteByte(')') return builder.String() diff --git a/entc/integration/privacy/ent/task_create.go b/entc/integration/privacy/ent/task_create.go index 62f92848d1..d75e9ecdbb 100644 --- a/entc/integration/privacy/ent/task_create.go +++ b/entc/integration/privacy/ent/task_create.go @@ -354,11 +354,11 @@ func (tcb *TaskCreateBulk) Save(ctx context.Context) ([]*Task, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/entc/integration/privacy/ent/team.go b/entc/integration/privacy/ent/team.go index 869111536b..7e8333665b 100644 --- a/entc/integration/privacy/ent/team.go +++ b/entc/integration/privacy/ent/team.go @@ -128,8 +128,8 @@ func (t *Team) Unwrap() *Team { func (t *Team) String() string { var builder strings.Builder builder.WriteString("Team(") - builder.WriteString(fmt.Sprintf("id=%v", t.ID)) - builder.WriteString(", name=") + builder.WriteString(fmt.Sprintf("id=%v, ", t.ID)) + builder.WriteString("name=") builder.WriteString(t.Name) builder.WriteByte(')') return builder.String() diff --git a/entc/integration/privacy/ent/team_create.go b/entc/integration/privacy/ent/team_create.go index 939da4b41d..2d27b17730 100644 --- a/entc/integration/privacy/ent/team_create.go +++ b/entc/integration/privacy/ent/team_create.go @@ -261,11 +261,11 @@ func (tcb *TeamCreateBulk) Save(ctx context.Context) ([]*Team, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/entc/integration/privacy/ent/user.go b/entc/integration/privacy/ent/user.go index 70584f750f..1ccc866421 100644 --- a/entc/integration/privacy/ent/user.go +++ b/entc/integration/privacy/ent/user.go @@ -136,10 +136,11 @@ func (u *User) Unwrap() *User { func (u *User) String() string { var builder strings.Builder builder.WriteString("User(") - builder.WriteString(fmt.Sprintf("id=%v", u.ID)) - builder.WriteString(", name=") + builder.WriteString(fmt.Sprintf("id=%v, ", u.ID)) + builder.WriteString("name=") builder.WriteString(u.Name) - builder.WriteString(", age=") + builder.WriteString(", ") + builder.WriteString("age=") builder.WriteString(fmt.Sprintf("%v", u.Age)) builder.WriteByte(')') return builder.String() diff --git a/entc/integration/privacy/ent/user_create.go b/entc/integration/privacy/ent/user_create.go index 6dfa80c0af..0ffd4fa82f 100644 --- a/entc/integration/privacy/ent/user_create.go +++ b/entc/integration/privacy/ent/user_create.go @@ -283,11 +283,11 @@ func (ucb *UserCreateBulk) Save(ctx context.Context) ([]*User, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/entc/integration/template/ent/client.go b/entc/integration/template/ent/client.go index 0cb6ee6079..ddc50f193b 100644 --- a/entc/integration/template/ent/client.go +++ b/entc/integration/template/ent/client.go @@ -166,7 +166,7 @@ func (c *GroupClient) Use(hooks ...Hook) { c.hooks.Group = append(c.hooks.Group, hooks...) } -// Create returns a create builder for Group. +// Create returns a builder for creating a Group entity. func (c *GroupClient) Create() *GroupCreate { mutation := newGroupMutation(c.config, OpCreate) return &GroupCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -201,12 +201,12 @@ func (c *GroupClient) Delete() *GroupDelete { return &GroupDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *GroupClient) DeleteOne(gr *Group) *GroupDeleteOne { return c.DeleteOneID(gr.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *GroupClient) DeleteOneID(id int) *GroupDeleteOne { builder := c.Delete().Where(group.ID(id)) builder.mutation.id = &id @@ -257,7 +257,7 @@ func (c *PetClient) Use(hooks ...Hook) { c.hooks.Pet = append(c.hooks.Pet, hooks...) } -// Create returns a create builder for Pet. +// Create returns a builder for creating a Pet entity. func (c *PetClient) Create() *PetCreate { mutation := newPetMutation(c.config, OpCreate) return &PetCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -292,12 +292,12 @@ func (c *PetClient) Delete() *PetDelete { return &PetDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *PetClient) DeleteOne(pe *Pet) *PetDeleteOne { return c.DeleteOneID(pe.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *PetClient) DeleteOneID(id int) *PetDeleteOne { builder := c.Delete().Where(pet.ID(id)) builder.mutation.id = &id @@ -364,7 +364,7 @@ func (c *UserClient) Use(hooks ...Hook) { c.hooks.User = append(c.hooks.User, hooks...) } -// Create returns a create builder for User. +// Create returns a builder for creating a User entity. func (c *UserClient) Create() *UserCreate { mutation := newUserMutation(c.config, OpCreate) return &UserCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -399,12 +399,12 @@ func (c *UserClient) Delete() *UserDelete { return &UserDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *UserClient) DeleteOne(u *User) *UserDeleteOne { return c.DeleteOneID(u.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *UserClient) DeleteOneID(id int) *UserDeleteOne { builder := c.Delete().Where(user.ID(id)) builder.mutation.id = &id diff --git a/entc/integration/template/ent/group_create.go b/entc/integration/template/ent/group_create.go index b1894ae05d..cfdeb07159 100644 --- a/entc/integration/template/ent/group_create.go +++ b/entc/integration/template/ent/group_create.go @@ -186,11 +186,11 @@ func (gcb *GroupCreateBulk) Save(ctx context.Context) ([]*Group, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/entc/integration/template/ent/pet_create.go b/entc/integration/template/ent/pet_create.go index 8ea9aef642..dd7586dafe 100644 --- a/entc/integration/template/ent/pet_create.go +++ b/entc/integration/template/ent/pet_create.go @@ -249,11 +249,11 @@ func (pcb *PetCreateBulk) Save(ctx context.Context) ([]*Pet, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/entc/integration/template/ent/user_create.go b/entc/integration/template/ent/user_create.go index ce2b5531df..50d5e6e97c 100644 --- a/entc/integration/template/ent/user_create.go +++ b/entc/integration/template/ent/user_create.go @@ -255,11 +255,11 @@ func (ucb *UserCreateBulk) Save(ctx context.Context) ([]*User, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/entc/load/schema.go b/entc/load/schema.go index 8db8d4277c..5217bfab95 100644 --- a/entc/load/schema.go +++ b/entc/load/schema.go @@ -67,6 +67,7 @@ type Edge struct { Field string `json:"field,omitempty"` RefName string `json:"ref_name,omitempty"` Ref *Edge `json:"ref,omitempty"` + Through *struct{ N, T string } `json:"through,omitempty"` Unique bool `json:"unique,omitempty"` Inverse bool `json:"inverse,omitempty"` Required bool `json:"required,omitempty"` @@ -94,6 +95,7 @@ func NewEdge(ed *edge.Descriptor) *Edge { Inverse: ed.Inverse, Required: ed.Required, RefName: ed.RefName, + Through: ed.Through, StorageKey: ed.StorageKey, Annotations: make(map[string]interface{}), } diff --git a/examples/edgeindex/ent/city.go b/examples/edgeindex/ent/city.go index 17acca9f79..271df09176 100644 --- a/examples/edgeindex/ent/city.go +++ b/examples/edgeindex/ent/city.go @@ -112,8 +112,8 @@ func (c *City) Unwrap() *City { func (c *City) String() string { var builder strings.Builder builder.WriteString("City(") - builder.WriteString(fmt.Sprintf("id=%v", c.ID)) - builder.WriteString(", name=") + builder.WriteString(fmt.Sprintf("id=%v, ", c.ID)) + builder.WriteString("name=") builder.WriteString(c.Name) builder.WriteByte(')') return builder.String() diff --git a/examples/edgeindex/ent/city_create.go b/examples/edgeindex/ent/city_create.go index 085d969adc..0eb70ebf6a 100644 --- a/examples/edgeindex/ent/city_create.go +++ b/examples/edgeindex/ent/city_create.go @@ -221,11 +221,11 @@ func (ccb *CityCreateBulk) Save(ctx context.Context) ([]*City, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/examples/edgeindex/ent/client.go b/examples/edgeindex/ent/client.go index cf8ccd7dcb..f419e6dbdf 100644 --- a/examples/edgeindex/ent/client.go +++ b/examples/edgeindex/ent/client.go @@ -150,7 +150,7 @@ func (c *CityClient) Use(hooks ...Hook) { c.hooks.City = append(c.hooks.City, hooks...) } -// Create returns a create builder for City. +// Create returns a builder for creating a City entity. func (c *CityClient) Create() *CityCreate { mutation := newCityMutation(c.config, OpCreate) return &CityCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -185,12 +185,12 @@ func (c *CityClient) Delete() *CityDelete { return &CityDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *CityClient) DeleteOne(ci *City) *CityDeleteOne { return c.DeleteOneID(ci.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *CityClient) DeleteOneID(id int) *CityDeleteOne { builder := c.Delete().Where(city.ID(id)) builder.mutation.id = &id @@ -256,7 +256,7 @@ func (c *StreetClient) Use(hooks ...Hook) { c.hooks.Street = append(c.hooks.Street, hooks...) } -// Create returns a create builder for Street. +// Create returns a builder for creating a Street entity. func (c *StreetClient) Create() *StreetCreate { mutation := newStreetMutation(c.config, OpCreate) return &StreetCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -291,12 +291,12 @@ func (c *StreetClient) Delete() *StreetDelete { return &StreetDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *StreetClient) DeleteOne(s *Street) *StreetDeleteOne { return c.DeleteOneID(s.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *StreetClient) DeleteOneID(id int) *StreetDeleteOne { builder := c.Delete().Where(street.ID(id)) builder.mutation.id = &id diff --git a/examples/edgeindex/ent/street.go b/examples/edgeindex/ent/street.go index faa89c82c2..72fab3b81f 100644 --- a/examples/edgeindex/ent/street.go +++ b/examples/edgeindex/ent/street.go @@ -128,8 +128,8 @@ func (s *Street) Unwrap() *Street { func (s *Street) String() string { var builder strings.Builder builder.WriteString("Street(") - builder.WriteString(fmt.Sprintf("id=%v", s.ID)) - builder.WriteString(", name=") + builder.WriteString(fmt.Sprintf("id=%v, ", s.ID)) + builder.WriteString("name=") builder.WriteString(s.Name) builder.WriteByte(')') return builder.String() diff --git a/examples/edgeindex/ent/street_create.go b/examples/edgeindex/ent/street_create.go index a6420ef2d2..434ff0fd7a 100644 --- a/examples/edgeindex/ent/street_create.go +++ b/examples/edgeindex/ent/street_create.go @@ -226,11 +226,11 @@ func (scb *StreetCreateBulk) Save(ctx context.Context) ([]*Street, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/examples/entcpkg/ent/client.go b/examples/entcpkg/ent/client.go index a58097bd67..72cfa9bbd2 100644 --- a/examples/entcpkg/ent/client.go +++ b/examples/entcpkg/ent/client.go @@ -142,7 +142,7 @@ func (c *UserClient) Use(hooks ...Hook) { c.hooks.User = append(c.hooks.User, hooks...) } -// Create returns a create builder for User. +// Create returns a builder for creating a User entity. func (c *UserClient) Create() *UserCreate { mutation := newUserMutation(c.config, OpCreate) return &UserCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -177,12 +177,12 @@ func (c *UserClient) Delete() *UserDelete { return &UserDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *UserClient) DeleteOne(u *User) *UserDeleteOne { return c.DeleteOneID(u.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *UserClient) DeleteOneID(id int) *UserDeleteOne { builder := c.Delete().Where(user.ID(id)) builder.mutation.id = &id diff --git a/examples/entcpkg/ent/user.go b/examples/entcpkg/ent/user.go index 92b753f1a8..cf1cc9543a 100644 --- a/examples/entcpkg/ent/user.go +++ b/examples/entcpkg/ent/user.go @@ -97,10 +97,11 @@ func (u *User) Unwrap() *User { func (u *User) String() string { var builder strings.Builder builder.WriteString("User(") - builder.WriteString(fmt.Sprintf("id=%v", u.ID)) - builder.WriteString(", name=") + builder.WriteString(fmt.Sprintf("id=%v, ", u.ID)) + builder.WriteString("name=") builder.WriteString(u.Name) - builder.WriteString(", age=") + builder.WriteString(", ") + builder.WriteString("age=") builder.WriteString(fmt.Sprintf("%v", u.Age)) builder.WriteByte(')') return builder.String() diff --git a/examples/entcpkg/ent/user_create.go b/examples/entcpkg/ent/user_create.go index 6891b035ab..a2f305b340 100644 --- a/examples/entcpkg/ent/user_create.go +++ b/examples/entcpkg/ent/user_create.go @@ -212,11 +212,11 @@ func (ucb *UserCreateBulk) Save(ctx context.Context) ([]*User, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/examples/fs/ent/client.go b/examples/fs/ent/client.go index 1b3b200ba6..c46c39d581 100644 --- a/examples/fs/ent/client.go +++ b/examples/fs/ent/client.go @@ -143,7 +143,7 @@ func (c *FileClient) Use(hooks ...Hook) { c.hooks.File = append(c.hooks.File, hooks...) } -// Create returns a create builder for File. +// Create returns a builder for creating a File entity. func (c *FileClient) Create() *FileCreate { mutation := newFileMutation(c.config, OpCreate) return &FileCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -178,12 +178,12 @@ func (c *FileClient) Delete() *FileDelete { return &FileDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *FileClient) DeleteOne(f *File) *FileDeleteOne { return c.DeleteOneID(f.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *FileClient) DeleteOneID(id int) *FileDeleteOne { builder := c.Delete().Where(file.ID(id)) builder.mutation.id = &id diff --git a/examples/fs/ent/file.go b/examples/fs/ent/file.go index a2d79d9e8d..f0e13d31cd 100644 --- a/examples/fs/ent/file.go +++ b/examples/fs/ent/file.go @@ -151,12 +151,14 @@ func (f *File) Unwrap() *File { func (f *File) String() string { var builder strings.Builder builder.WriteString("File(") - builder.WriteString(fmt.Sprintf("id=%v", f.ID)) - builder.WriteString(", name=") + builder.WriteString(fmt.Sprintf("id=%v, ", f.ID)) + builder.WriteString("name=") builder.WriteString(f.Name) - builder.WriteString(", deleted=") + builder.WriteString(", ") + builder.WriteString("deleted=") builder.WriteString(fmt.Sprintf("%v", f.Deleted)) - builder.WriteString(", parent_id=") + builder.WriteString(", ") + builder.WriteString("parent_id=") builder.WriteString(fmt.Sprintf("%v", f.ParentID)) builder.WriteByte(')') return builder.String() diff --git a/examples/fs/ent/file_create.go b/examples/fs/ent/file_create.go index 15f065b2db..c9a2f31f14 100644 --- a/examples/fs/ent/file_create.go +++ b/examples/fs/ent/file_create.go @@ -294,11 +294,11 @@ func (fcb *FileCreateBulk) Save(ctx context.Context) ([]*File, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/examples/m2m2types/ent/client.go b/examples/m2m2types/ent/client.go index d23e892ed2..cdf08ec840 100644 --- a/examples/m2m2types/ent/client.go +++ b/examples/m2m2types/ent/client.go @@ -150,7 +150,7 @@ func (c *GroupClient) Use(hooks ...Hook) { c.hooks.Group = append(c.hooks.Group, hooks...) } -// Create returns a create builder for Group. +// Create returns a builder for creating a Group entity. func (c *GroupClient) Create() *GroupCreate { mutation := newGroupMutation(c.config, OpCreate) return &GroupCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -185,12 +185,12 @@ func (c *GroupClient) Delete() *GroupDelete { return &GroupDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *GroupClient) DeleteOne(gr *Group) *GroupDeleteOne { return c.DeleteOneID(gr.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *GroupClient) DeleteOneID(id int) *GroupDeleteOne { builder := c.Delete().Where(group.ID(id)) builder.mutation.id = &id @@ -256,7 +256,7 @@ func (c *UserClient) Use(hooks ...Hook) { c.hooks.User = append(c.hooks.User, hooks...) } -// Create returns a create builder for User. +// Create returns a builder for creating a User entity. func (c *UserClient) Create() *UserCreate { mutation := newUserMutation(c.config, OpCreate) return &UserCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -291,12 +291,12 @@ func (c *UserClient) Delete() *UserDelete { return &UserDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *UserClient) DeleteOne(u *User) *UserDeleteOne { return c.DeleteOneID(u.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *UserClient) DeleteOneID(id int) *UserDeleteOne { builder := c.Delete().Where(user.ID(id)) builder.mutation.id = &id diff --git a/examples/m2m2types/ent/group.go b/examples/m2m2types/ent/group.go index 156fd5530c..11c46f3423 100644 --- a/examples/m2m2types/ent/group.go +++ b/examples/m2m2types/ent/group.go @@ -112,8 +112,8 @@ func (gr *Group) Unwrap() *Group { func (gr *Group) String() string { var builder strings.Builder builder.WriteString("Group(") - builder.WriteString(fmt.Sprintf("id=%v", gr.ID)) - builder.WriteString(", name=") + builder.WriteString(fmt.Sprintf("id=%v, ", gr.ID)) + builder.WriteString("name=") builder.WriteString(gr.Name) builder.WriteByte(')') return builder.String() diff --git a/examples/m2m2types/ent/group_create.go b/examples/m2m2types/ent/group_create.go index 2ae85d9427..dd574220d1 100644 --- a/examples/m2m2types/ent/group_create.go +++ b/examples/m2m2types/ent/group_create.go @@ -221,11 +221,11 @@ func (gcb *GroupCreateBulk) Save(ctx context.Context) ([]*Group, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/examples/m2m2types/ent/user.go b/examples/m2m2types/ent/user.go index 3c489d7ca3..6912bf59a6 100644 --- a/examples/m2m2types/ent/user.go +++ b/examples/m2m2types/ent/user.go @@ -120,10 +120,11 @@ func (u *User) Unwrap() *User { func (u *User) String() string { var builder strings.Builder builder.WriteString("User(") - builder.WriteString(fmt.Sprintf("id=%v", u.ID)) - builder.WriteString(", age=") + builder.WriteString(fmt.Sprintf("id=%v, ", u.ID)) + builder.WriteString("age=") builder.WriteString(fmt.Sprintf("%v", u.Age)) - builder.WriteString(", name=") + builder.WriteString(", ") + builder.WriteString("name=") builder.WriteString(u.Name) builder.WriteByte(')') return builder.String() diff --git a/examples/m2m2types/ent/user_create.go b/examples/m2m2types/ent/user_create.go index c92e050296..56dc47f5ca 100644 --- a/examples/m2m2types/ent/user_create.go +++ b/examples/m2m2types/ent/user_create.go @@ -238,11 +238,11 @@ func (ucb *UserCreateBulk) Save(ctx context.Context) ([]*User, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/examples/m2mbidi/ent/client.go b/examples/m2mbidi/ent/client.go index fe9f3898e6..1ddbf236f9 100644 --- a/examples/m2mbidi/ent/client.go +++ b/examples/m2mbidi/ent/client.go @@ -143,7 +143,7 @@ func (c *UserClient) Use(hooks ...Hook) { c.hooks.User = append(c.hooks.User, hooks...) } -// Create returns a create builder for User. +// Create returns a builder for creating a User entity. func (c *UserClient) Create() *UserCreate { mutation := newUserMutation(c.config, OpCreate) return &UserCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -178,12 +178,12 @@ func (c *UserClient) Delete() *UserDelete { return &UserDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *UserClient) DeleteOne(u *User) *UserDeleteOne { return c.DeleteOneID(u.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *UserClient) DeleteOneID(id int) *UserDeleteOne { builder := c.Delete().Where(user.ID(id)) builder.mutation.id = &id diff --git a/examples/m2mbidi/ent/user.go b/examples/m2mbidi/ent/user.go index 1cc11fd2ed..03666d5829 100644 --- a/examples/m2mbidi/ent/user.go +++ b/examples/m2mbidi/ent/user.go @@ -120,10 +120,11 @@ func (u *User) Unwrap() *User { func (u *User) String() string { var builder strings.Builder builder.WriteString("User(") - builder.WriteString(fmt.Sprintf("id=%v", u.ID)) - builder.WriteString(", age=") + builder.WriteString(fmt.Sprintf("id=%v, ", u.ID)) + builder.WriteString("age=") builder.WriteString(fmt.Sprintf("%v", u.Age)) - builder.WriteString(", name=") + builder.WriteString(", ") + builder.WriteString("name=") builder.WriteString(u.Name) builder.WriteByte(')') return builder.String() diff --git a/examples/m2mbidi/ent/user_create.go b/examples/m2mbidi/ent/user_create.go index 9ad2427111..589b29c7c7 100644 --- a/examples/m2mbidi/ent/user_create.go +++ b/examples/m2mbidi/ent/user_create.go @@ -237,11 +237,11 @@ func (ucb *UserCreateBulk) Save(ctx context.Context) ([]*User, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/examples/m2mrecur/ent/client.go b/examples/m2mrecur/ent/client.go index a3bfab8739..ae1e52dbc0 100644 --- a/examples/m2mrecur/ent/client.go +++ b/examples/m2mrecur/ent/client.go @@ -143,7 +143,7 @@ func (c *UserClient) Use(hooks ...Hook) { c.hooks.User = append(c.hooks.User, hooks...) } -// Create returns a create builder for User. +// Create returns a builder for creating a User entity. func (c *UserClient) Create() *UserCreate { mutation := newUserMutation(c.config, OpCreate) return &UserCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -178,12 +178,12 @@ func (c *UserClient) Delete() *UserDelete { return &UserDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *UserClient) DeleteOne(u *User) *UserDeleteOne { return c.DeleteOneID(u.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *UserClient) DeleteOneID(id int) *UserDeleteOne { builder := c.Delete().Where(user.ID(id)) builder.mutation.id = &id diff --git a/examples/m2mrecur/ent/user.go b/examples/m2mrecur/ent/user.go index 83a7d85408..fccec625ef 100644 --- a/examples/m2mrecur/ent/user.go +++ b/examples/m2mrecur/ent/user.go @@ -136,10 +136,11 @@ func (u *User) Unwrap() *User { func (u *User) String() string { var builder strings.Builder builder.WriteString("User(") - builder.WriteString(fmt.Sprintf("id=%v", u.ID)) - builder.WriteString(", age=") + builder.WriteString(fmt.Sprintf("id=%v, ", u.ID)) + builder.WriteString("age=") builder.WriteString(fmt.Sprintf("%v", u.Age)) - builder.WriteString(", name=") + builder.WriteString(", ") + builder.WriteString("name=") builder.WriteString(u.Name) builder.WriteByte(')') return builder.String() diff --git a/examples/m2mrecur/ent/user_create.go b/examples/m2mrecur/ent/user_create.go index 2b93337330..fb7753d737 100644 --- a/examples/m2mrecur/ent/user_create.go +++ b/examples/m2mrecur/ent/user_create.go @@ -271,11 +271,11 @@ func (ucb *UserCreateBulk) Save(ctx context.Context) ([]*User, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/examples/o2m2types/ent/client.go b/examples/o2m2types/ent/client.go index 1e3fb5a623..bbf96eec60 100644 --- a/examples/o2m2types/ent/client.go +++ b/examples/o2m2types/ent/client.go @@ -150,7 +150,7 @@ func (c *PetClient) Use(hooks ...Hook) { c.hooks.Pet = append(c.hooks.Pet, hooks...) } -// Create returns a create builder for Pet. +// Create returns a builder for creating a Pet entity. func (c *PetClient) Create() *PetCreate { mutation := newPetMutation(c.config, OpCreate) return &PetCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -185,12 +185,12 @@ func (c *PetClient) Delete() *PetDelete { return &PetDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *PetClient) DeleteOne(pe *Pet) *PetDeleteOne { return c.DeleteOneID(pe.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *PetClient) DeleteOneID(id int) *PetDeleteOne { builder := c.Delete().Where(pet.ID(id)) builder.mutation.id = &id @@ -256,7 +256,7 @@ func (c *UserClient) Use(hooks ...Hook) { c.hooks.User = append(c.hooks.User, hooks...) } -// Create returns a create builder for User. +// Create returns a builder for creating a User entity. func (c *UserClient) Create() *UserCreate { mutation := newUserMutation(c.config, OpCreate) return &UserCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -291,12 +291,12 @@ func (c *UserClient) Delete() *UserDelete { return &UserDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *UserClient) DeleteOne(u *User) *UserDeleteOne { return c.DeleteOneID(u.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *UserClient) DeleteOneID(id int) *UserDeleteOne { builder := c.Delete().Where(user.ID(id)) builder.mutation.id = &id diff --git a/examples/o2m2types/ent/pet.go b/examples/o2m2types/ent/pet.go index ced393fac5..8a3860ca9a 100644 --- a/examples/o2m2types/ent/pet.go +++ b/examples/o2m2types/ent/pet.go @@ -128,8 +128,8 @@ func (pe *Pet) Unwrap() *Pet { func (pe *Pet) String() string { var builder strings.Builder builder.WriteString("Pet(") - builder.WriteString(fmt.Sprintf("id=%v", pe.ID)) - builder.WriteString(", name=") + builder.WriteString(fmt.Sprintf("id=%v, ", pe.ID)) + builder.WriteString("name=") builder.WriteString(pe.Name) builder.WriteByte(')') return builder.String() diff --git a/examples/o2m2types/ent/pet_create.go b/examples/o2m2types/ent/pet_create.go index 4fc5f50023..9a01676bff 100644 --- a/examples/o2m2types/ent/pet_create.go +++ b/examples/o2m2types/ent/pet_create.go @@ -226,11 +226,11 @@ func (pcb *PetCreateBulk) Save(ctx context.Context) ([]*Pet, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/examples/o2m2types/ent/user.go b/examples/o2m2types/ent/user.go index 0acc39eb5f..89913e9a1e 100644 --- a/examples/o2m2types/ent/user.go +++ b/examples/o2m2types/ent/user.go @@ -120,10 +120,11 @@ func (u *User) Unwrap() *User { func (u *User) String() string { var builder strings.Builder builder.WriteString("User(") - builder.WriteString(fmt.Sprintf("id=%v", u.ID)) - builder.WriteString(", age=") + builder.WriteString(fmt.Sprintf("id=%v, ", u.ID)) + builder.WriteString("age=") builder.WriteString(fmt.Sprintf("%v", u.Age)) - builder.WriteString(", name=") + builder.WriteString(", ") + builder.WriteString("name=") builder.WriteString(u.Name) builder.WriteByte(')') return builder.String() diff --git a/examples/o2m2types/ent/user_create.go b/examples/o2m2types/ent/user_create.go index c803f77fc9..abc4bb324a 100644 --- a/examples/o2m2types/ent/user_create.go +++ b/examples/o2m2types/ent/user_create.go @@ -238,11 +238,11 @@ func (ucb *UserCreateBulk) Save(ctx context.Context) ([]*User, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/examples/o2mrecur/ent/client.go b/examples/o2mrecur/ent/client.go index 6d11d4b7f7..23bab42427 100644 --- a/examples/o2mrecur/ent/client.go +++ b/examples/o2mrecur/ent/client.go @@ -143,7 +143,7 @@ func (c *NodeClient) Use(hooks ...Hook) { c.hooks.Node = append(c.hooks.Node, hooks...) } -// Create returns a create builder for Node. +// Create returns a builder for creating a Node entity. func (c *NodeClient) Create() *NodeCreate { mutation := newNodeMutation(c.config, OpCreate) return &NodeCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -178,12 +178,12 @@ func (c *NodeClient) Delete() *NodeDelete { return &NodeDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *NodeClient) DeleteOne(n *Node) *NodeDeleteOne { return c.DeleteOneID(n.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *NodeClient) DeleteOneID(id int) *NodeDeleteOne { builder := c.Delete().Where(node.ID(id)) builder.mutation.id = &id diff --git a/examples/o2mrecur/ent/node.go b/examples/o2mrecur/ent/node.go index f5fc72969d..286a49e2ab 100644 --- a/examples/o2mrecur/ent/node.go +++ b/examples/o2mrecur/ent/node.go @@ -141,8 +141,8 @@ func (n *Node) Unwrap() *Node { func (n *Node) String() string { var builder strings.Builder builder.WriteString("Node(") - builder.WriteString(fmt.Sprintf("id=%v", n.ID)) - builder.WriteString(", value=") + builder.WriteString(fmt.Sprintf("id=%v, ", n.ID)) + builder.WriteString("value=") builder.WriteString(fmt.Sprintf("%v", n.Value)) builder.WriteByte(')') return builder.String() diff --git a/examples/o2mrecur/ent/node_create.go b/examples/o2mrecur/ent/node_create.go index 986274c512..f45eaff1f9 100644 --- a/examples/o2mrecur/ent/node_create.go +++ b/examples/o2mrecur/ent/node_create.go @@ -259,11 +259,11 @@ func (ncb *NodeCreateBulk) Save(ctx context.Context) ([]*Node, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/examples/o2o2types/ent/card.go b/examples/o2o2types/ent/card.go index 56be63c37a..986fff59d7 100644 --- a/examples/o2o2types/ent/card.go +++ b/examples/o2o2types/ent/card.go @@ -139,10 +139,11 @@ func (c *Card) Unwrap() *Card { func (c *Card) String() string { var builder strings.Builder builder.WriteString("Card(") - builder.WriteString(fmt.Sprintf("id=%v", c.ID)) - builder.WriteString(", expired=") + builder.WriteString(fmt.Sprintf("id=%v, ", c.ID)) + builder.WriteString("expired=") builder.WriteString(c.Expired.Format(time.ANSIC)) - builder.WriteString(", number=") + builder.WriteString(", ") + builder.WriteString("number=") builder.WriteString(c.Number) builder.WriteByte(')') return builder.String() diff --git a/examples/o2o2types/ent/card_create.go b/examples/o2o2types/ent/card_create.go index d32668e15f..9d120bc8dc 100644 --- a/examples/o2o2types/ent/card_create.go +++ b/examples/o2o2types/ent/card_create.go @@ -239,11 +239,11 @@ func (ccb *CardCreateBulk) Save(ctx context.Context) ([]*Card, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/examples/o2o2types/ent/client.go b/examples/o2o2types/ent/client.go index 738b2a259c..8e61b11c59 100644 --- a/examples/o2o2types/ent/client.go +++ b/examples/o2o2types/ent/client.go @@ -150,7 +150,7 @@ func (c *CardClient) Use(hooks ...Hook) { c.hooks.Card = append(c.hooks.Card, hooks...) } -// Create returns a create builder for Card. +// Create returns a builder for creating a Card entity. func (c *CardClient) Create() *CardCreate { mutation := newCardMutation(c.config, OpCreate) return &CardCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -185,12 +185,12 @@ func (c *CardClient) Delete() *CardDelete { return &CardDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *CardClient) DeleteOne(ca *Card) *CardDeleteOne { return c.DeleteOneID(ca.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *CardClient) DeleteOneID(id int) *CardDeleteOne { builder := c.Delete().Where(card.ID(id)) builder.mutation.id = &id @@ -256,7 +256,7 @@ func (c *UserClient) Use(hooks ...Hook) { c.hooks.User = append(c.hooks.User, hooks...) } -// Create returns a create builder for User. +// Create returns a builder for creating a User entity. func (c *UserClient) Create() *UserCreate { mutation := newUserMutation(c.config, OpCreate) return &UserCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -291,12 +291,12 @@ func (c *UserClient) Delete() *UserDelete { return &UserDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *UserClient) DeleteOne(u *User) *UserDeleteOne { return c.DeleteOneID(u.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *UserClient) DeleteOneID(id int) *UserDeleteOne { builder := c.Delete().Where(user.ID(id)) builder.mutation.id = &id diff --git a/examples/o2o2types/ent/user.go b/examples/o2o2types/ent/user.go index f8b95bbde4..a08bb9c8e9 100644 --- a/examples/o2o2types/ent/user.go +++ b/examples/o2o2types/ent/user.go @@ -126,10 +126,11 @@ func (u *User) Unwrap() *User { func (u *User) String() string { var builder strings.Builder builder.WriteString("User(") - builder.WriteString(fmt.Sprintf("id=%v", u.ID)) - builder.WriteString(", age=") + builder.WriteString(fmt.Sprintf("id=%v, ", u.ID)) + builder.WriteString("age=") builder.WriteString(fmt.Sprintf("%v", u.Age)) - builder.WriteString(", name=") + builder.WriteString(", ") + builder.WriteString("name=") builder.WriteString(u.Name) builder.WriteByte(')') return builder.String() diff --git a/examples/o2o2types/ent/user_create.go b/examples/o2o2types/ent/user_create.go index a8d66dc217..159f0f6aa0 100644 --- a/examples/o2o2types/ent/user_create.go +++ b/examples/o2o2types/ent/user_create.go @@ -242,11 +242,11 @@ func (ucb *UserCreateBulk) Save(ctx context.Context) ([]*User, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/examples/o2obidi/ent/client.go b/examples/o2obidi/ent/client.go index 7d67e1c9ca..0bc6c68a92 100644 --- a/examples/o2obidi/ent/client.go +++ b/examples/o2obidi/ent/client.go @@ -143,7 +143,7 @@ func (c *UserClient) Use(hooks ...Hook) { c.hooks.User = append(c.hooks.User, hooks...) } -// Create returns a create builder for User. +// Create returns a builder for creating a User entity. func (c *UserClient) Create() *UserCreate { mutation := newUserMutation(c.config, OpCreate) return &UserCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -178,12 +178,12 @@ func (c *UserClient) Delete() *UserDelete { return &UserDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *UserClient) DeleteOne(u *User) *UserDeleteOne { return c.DeleteOneID(u.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *UserClient) DeleteOneID(id int) *UserDeleteOne { builder := c.Delete().Where(user.ID(id)) builder.mutation.id = &id diff --git a/examples/o2obidi/ent/user.go b/examples/o2obidi/ent/user.go index f05c1fdc50..438133ff3e 100644 --- a/examples/o2obidi/ent/user.go +++ b/examples/o2obidi/ent/user.go @@ -135,10 +135,11 @@ func (u *User) Unwrap() *User { func (u *User) String() string { var builder strings.Builder builder.WriteString("User(") - builder.WriteString(fmt.Sprintf("id=%v", u.ID)) - builder.WriteString(", age=") + builder.WriteString(fmt.Sprintf("id=%v, ", u.ID)) + builder.WriteString("age=") builder.WriteString(fmt.Sprintf("%v", u.Age)) - builder.WriteString(", name=") + builder.WriteString(", ") + builder.WriteString("name=") builder.WriteString(u.Name) builder.WriteByte(')') return builder.String() diff --git a/examples/o2obidi/ent/user_create.go b/examples/o2obidi/ent/user_create.go index d3a5a61630..fe43037faf 100644 --- a/examples/o2obidi/ent/user_create.go +++ b/examples/o2obidi/ent/user_create.go @@ -242,11 +242,11 @@ func (ucb *UserCreateBulk) Save(ctx context.Context) ([]*User, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/examples/o2orecur/ent/client.go b/examples/o2orecur/ent/client.go index 0adba589c8..f134f87277 100644 --- a/examples/o2orecur/ent/client.go +++ b/examples/o2orecur/ent/client.go @@ -143,7 +143,7 @@ func (c *NodeClient) Use(hooks ...Hook) { c.hooks.Node = append(c.hooks.Node, hooks...) } -// Create returns a create builder for Node. +// Create returns a builder for creating a Node entity. func (c *NodeClient) Create() *NodeCreate { mutation := newNodeMutation(c.config, OpCreate) return &NodeCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -178,12 +178,12 @@ func (c *NodeClient) Delete() *NodeDelete { return &NodeDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *NodeClient) DeleteOne(n *Node) *NodeDeleteOne { return c.DeleteOneID(n.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *NodeClient) DeleteOneID(id int) *NodeDeleteOne { builder := c.Delete().Where(node.ID(id)) builder.mutation.id = &id diff --git a/examples/o2orecur/ent/node.go b/examples/o2orecur/ent/node.go index 9aa8ebffb2..68235cbdee 100644 --- a/examples/o2orecur/ent/node.go +++ b/examples/o2orecur/ent/node.go @@ -146,8 +146,8 @@ func (n *Node) Unwrap() *Node { func (n *Node) String() string { var builder strings.Builder builder.WriteString("Node(") - builder.WriteString(fmt.Sprintf("id=%v", n.ID)) - builder.WriteString(", value=") + builder.WriteString(fmt.Sprintf("id=%v, ", n.ID)) + builder.WriteString("value=") builder.WriteString(fmt.Sprintf("%v", n.Value)) builder.WriteByte(')') return builder.String() diff --git a/examples/o2orecur/ent/node_create.go b/examples/o2orecur/ent/node_create.go index cb5d847db4..a5acefefea 100644 --- a/examples/o2orecur/ent/node_create.go +++ b/examples/o2orecur/ent/node_create.go @@ -263,11 +263,11 @@ func (ncb *NodeCreateBulk) Save(ctx context.Context) ([]*Node, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/examples/privacyadmin/ent/client.go b/examples/privacyadmin/ent/client.go index f59d866e49..2f789ea4fe 100644 --- a/examples/privacyadmin/ent/client.go +++ b/examples/privacyadmin/ent/client.go @@ -142,7 +142,7 @@ func (c *UserClient) Use(hooks ...Hook) { c.hooks.User = append(c.hooks.User, hooks...) } -// Create returns a create builder for User. +// Create returns a builder for creating a User entity. func (c *UserClient) Create() *UserCreate { mutation := newUserMutation(c.config, OpCreate) return &UserCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -177,12 +177,12 @@ func (c *UserClient) Delete() *UserDelete { return &UserDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *UserClient) DeleteOne(u *User) *UserDeleteOne { return c.DeleteOneID(u.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *UserClient) DeleteOneID(id int) *UserDeleteOne { builder := c.Delete().Where(user.ID(id)) builder.mutation.id = &id diff --git a/examples/privacyadmin/ent/user.go b/examples/privacyadmin/ent/user.go index 8c5be3e570..013c72ff5a 100644 --- a/examples/privacyadmin/ent/user.go +++ b/examples/privacyadmin/ent/user.go @@ -86,8 +86,8 @@ func (u *User) Unwrap() *User { func (u *User) String() string { var builder strings.Builder builder.WriteString("User(") - builder.WriteString(fmt.Sprintf("id=%v", u.ID)) - builder.WriteString(", name=") + builder.WriteString(fmt.Sprintf("id=%v, ", u.ID)) + builder.WriteString("name=") builder.WriteString(u.Name) builder.WriteByte(')') return builder.String() diff --git a/examples/privacyadmin/ent/user_create.go b/examples/privacyadmin/ent/user_create.go index 074e2ce70d..87094d0eb5 100644 --- a/examples/privacyadmin/ent/user_create.go +++ b/examples/privacyadmin/ent/user_create.go @@ -207,11 +207,11 @@ func (ucb *UserCreateBulk) Save(ctx context.Context) ([]*User, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/examples/privacytenant/ent/client.go b/examples/privacytenant/ent/client.go index 1647966390..4dcd8fccca 100644 --- a/examples/privacytenant/ent/client.go +++ b/examples/privacytenant/ent/client.go @@ -157,7 +157,7 @@ func (c *GroupClient) Use(hooks ...Hook) { c.hooks.Group = append(c.hooks.Group, hooks...) } -// Create returns a create builder for Group. +// Create returns a builder for creating a Group entity. func (c *GroupClient) Create() *GroupCreate { mutation := newGroupMutation(c.config, OpCreate) return &GroupCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -192,12 +192,12 @@ func (c *GroupClient) Delete() *GroupDelete { return &GroupDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *GroupClient) DeleteOne(gr *Group) *GroupDeleteOne { return c.DeleteOneID(gr.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *GroupClient) DeleteOneID(id int) *GroupDeleteOne { builder := c.Delete().Where(group.ID(id)) builder.mutation.id = &id @@ -280,7 +280,7 @@ func (c *TenantClient) Use(hooks ...Hook) { c.hooks.Tenant = append(c.hooks.Tenant, hooks...) } -// Create returns a create builder for Tenant. +// Create returns a builder for creating a Tenant entity. func (c *TenantClient) Create() *TenantCreate { mutation := newTenantMutation(c.config, OpCreate) return &TenantCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -315,12 +315,12 @@ func (c *TenantClient) Delete() *TenantDelete { return &TenantDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *TenantClient) DeleteOne(t *Tenant) *TenantDeleteOne { return c.DeleteOneID(t.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *TenantClient) DeleteOneID(id int) *TenantDeleteOne { builder := c.Delete().Where(tenant.ID(id)) builder.mutation.id = &id @@ -371,7 +371,7 @@ func (c *UserClient) Use(hooks ...Hook) { c.hooks.User = append(c.hooks.User, hooks...) } -// Create returns a create builder for User. +// Create returns a builder for creating a User entity. func (c *UserClient) Create() *UserCreate { mutation := newUserMutation(c.config, OpCreate) return &UserCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -406,12 +406,12 @@ func (c *UserClient) Delete() *UserDelete { return &UserDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *UserClient) DeleteOne(u *User) *UserDeleteOne { return c.DeleteOneID(u.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *UserClient) DeleteOneID(id int) *UserDeleteOne { builder := c.Delete().Where(user.ID(id)) builder.mutation.id = &id diff --git a/examples/privacytenant/ent/group.go b/examples/privacytenant/ent/group.go index 879e478da8..b8d1d6ceb7 100644 --- a/examples/privacytenant/ent/group.go +++ b/examples/privacytenant/ent/group.go @@ -144,8 +144,8 @@ func (gr *Group) Unwrap() *Group { func (gr *Group) String() string { var builder strings.Builder builder.WriteString("Group(") - builder.WriteString(fmt.Sprintf("id=%v", gr.ID)) - builder.WriteString(", name=") + builder.WriteString(fmt.Sprintf("id=%v, ", gr.ID)) + builder.WriteString("name=") builder.WriteString(gr.Name) builder.WriteByte(')') return builder.String() diff --git a/examples/privacytenant/ent/group_create.go b/examples/privacytenant/ent/group_create.go index ac76504226..09e46662cf 100644 --- a/examples/privacytenant/ent/group_create.go +++ b/examples/privacytenant/ent/group_create.go @@ -277,11 +277,11 @@ func (gcb *GroupCreateBulk) Save(ctx context.Context) ([]*Group, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/examples/privacytenant/ent/tenant.go b/examples/privacytenant/ent/tenant.go index b2ce1d193a..74e52bd961 100644 --- a/examples/privacytenant/ent/tenant.go +++ b/examples/privacytenant/ent/tenant.go @@ -86,8 +86,8 @@ func (t *Tenant) Unwrap() *Tenant { func (t *Tenant) String() string { var builder strings.Builder builder.WriteString("Tenant(") - builder.WriteString(fmt.Sprintf("id=%v", t.ID)) - builder.WriteString(", name=") + builder.WriteString(fmt.Sprintf("id=%v, ", t.ID)) + builder.WriteString("name=") builder.WriteString(t.Name) builder.WriteByte(')') return builder.String() diff --git a/examples/privacytenant/ent/tenant_create.go b/examples/privacytenant/ent/tenant_create.go index ed7ef1b265..54bcc5d579 100644 --- a/examples/privacytenant/ent/tenant_create.go +++ b/examples/privacytenant/ent/tenant_create.go @@ -191,11 +191,11 @@ func (tcb *TenantCreateBulk) Save(ctx context.Context) ([]*Tenant, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/examples/privacytenant/ent/user.go b/examples/privacytenant/ent/user.go index 59808cefcf..9e2c0ae6c0 100644 --- a/examples/privacytenant/ent/user.go +++ b/examples/privacytenant/ent/user.go @@ -157,10 +157,11 @@ func (u *User) Unwrap() *User { func (u *User) String() string { var builder strings.Builder builder.WriteString("User(") - builder.WriteString(fmt.Sprintf("id=%v", u.ID)) - builder.WriteString(", name=") + builder.WriteString(fmt.Sprintf("id=%v, ", u.ID)) + builder.WriteString("name=") builder.WriteString(u.Name) - builder.WriteString(", foods=") + builder.WriteString(", ") + builder.WriteString("foods=") builder.WriteString(fmt.Sprintf("%v", u.Foods)) builder.WriteByte(')') return builder.String() diff --git a/examples/privacytenant/ent/user_create.go b/examples/privacytenant/ent/user_create.go index 8d59f9a1c2..f8c66afcb3 100644 --- a/examples/privacytenant/ent/user_create.go +++ b/examples/privacytenant/ent/user_create.go @@ -291,11 +291,11 @@ func (ucb *UserCreateBulk) Save(ctx context.Context) ([]*User, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/examples/start/ent/car.go b/examples/start/ent/car.go index d17a280877..a54c1e773c 100644 --- a/examples/start/ent/car.go +++ b/examples/start/ent/car.go @@ -139,10 +139,11 @@ func (c *Car) Unwrap() *Car { func (c *Car) String() string { var builder strings.Builder builder.WriteString("Car(") - builder.WriteString(fmt.Sprintf("id=%v", c.ID)) - builder.WriteString(", model=") + builder.WriteString(fmt.Sprintf("id=%v, ", c.ID)) + builder.WriteString("model=") builder.WriteString(c.Model) - builder.WriteString(", registered_at=") + builder.WriteString(", ") + builder.WriteString("registered_at=") builder.WriteString(c.RegisteredAt.Format(time.ANSIC)) builder.WriteByte(')') return builder.String() diff --git a/examples/start/ent/car_create.go b/examples/start/ent/car_create.go index 558e41e824..30d4c7668a 100644 --- a/examples/start/ent/car_create.go +++ b/examples/start/ent/car_create.go @@ -244,11 +244,11 @@ func (ccb *CarCreateBulk) Save(ctx context.Context) ([]*Car, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/examples/start/ent/client.go b/examples/start/ent/client.go index dc4eabbe32..1c74d6cb2f 100644 --- a/examples/start/ent/client.go +++ b/examples/start/ent/client.go @@ -157,7 +157,7 @@ func (c *CarClient) Use(hooks ...Hook) { c.hooks.Car = append(c.hooks.Car, hooks...) } -// Create returns a create builder for Car. +// Create returns a builder for creating a Car entity. func (c *CarClient) Create() *CarCreate { mutation := newCarMutation(c.config, OpCreate) return &CarCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -192,12 +192,12 @@ func (c *CarClient) Delete() *CarDelete { return &CarDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *CarClient) DeleteOne(ca *Car) *CarDeleteOne { return c.DeleteOneID(ca.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *CarClient) DeleteOneID(id int) *CarDeleteOne { builder := c.Delete().Where(car.ID(id)) builder.mutation.id = &id @@ -263,7 +263,7 @@ func (c *GroupClient) Use(hooks ...Hook) { c.hooks.Group = append(c.hooks.Group, hooks...) } -// Create returns a create builder for Group. +// Create returns a builder for creating a Group entity. func (c *GroupClient) Create() *GroupCreate { mutation := newGroupMutation(c.config, OpCreate) return &GroupCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -298,12 +298,12 @@ func (c *GroupClient) Delete() *GroupDelete { return &GroupDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *GroupClient) DeleteOne(gr *Group) *GroupDeleteOne { return c.DeleteOneID(gr.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *GroupClient) DeleteOneID(id int) *GroupDeleteOne { builder := c.Delete().Where(group.ID(id)) builder.mutation.id = &id @@ -369,7 +369,7 @@ func (c *UserClient) Use(hooks ...Hook) { c.hooks.User = append(c.hooks.User, hooks...) } -// Create returns a create builder for User. +// Create returns a builder for creating a User entity. func (c *UserClient) Create() *UserCreate { mutation := newUserMutation(c.config, OpCreate) return &UserCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -404,12 +404,12 @@ func (c *UserClient) Delete() *UserDelete { return &UserDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *UserClient) DeleteOne(u *User) *UserDeleteOne { return c.DeleteOneID(u.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *UserClient) DeleteOneID(id int) *UserDeleteOne { builder := c.Delete().Where(user.ID(id)) builder.mutation.id = &id diff --git a/examples/start/ent/group.go b/examples/start/ent/group.go index d10c91517c..ca93a65c7f 100644 --- a/examples/start/ent/group.go +++ b/examples/start/ent/group.go @@ -112,8 +112,8 @@ func (gr *Group) Unwrap() *Group { func (gr *Group) String() string { var builder strings.Builder builder.WriteString("Group(") - builder.WriteString(fmt.Sprintf("id=%v", gr.ID)) - builder.WriteString(", name=") + builder.WriteString(fmt.Sprintf("id=%v, ", gr.ID)) + builder.WriteString("name=") builder.WriteString(gr.Name) builder.WriteByte(')') return builder.String() diff --git a/examples/start/ent/group_create.go b/examples/start/ent/group_create.go index bf1ef844c7..32f91884b4 100644 --- a/examples/start/ent/group_create.go +++ b/examples/start/ent/group_create.go @@ -226,11 +226,11 @@ func (gcb *GroupCreateBulk) Save(ctx context.Context) ([]*Group, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/examples/start/ent/user.go b/examples/start/ent/user.go index 7ce8ffa7ce..5744de72a2 100644 --- a/examples/start/ent/user.go +++ b/examples/start/ent/user.go @@ -136,10 +136,11 @@ func (u *User) Unwrap() *User { func (u *User) String() string { var builder strings.Builder builder.WriteString("User(") - builder.WriteString(fmt.Sprintf("id=%v", u.ID)) - builder.WriteString(", age=") + builder.WriteString(fmt.Sprintf("id=%v, ", u.ID)) + builder.WriteString("age=") builder.WriteString(fmt.Sprintf("%v", u.Age)) - builder.WriteString(", name=") + builder.WriteString(", ") + builder.WriteString("name=") builder.WriteString(u.Name) builder.WriteByte(')') return builder.String() diff --git a/examples/start/ent/user_create.go b/examples/start/ent/user_create.go index c10dc2a647..87b792ef29 100644 --- a/examples/start/ent/user_create.go +++ b/examples/start/ent/user_create.go @@ -296,11 +296,11 @@ func (ucb *UserCreateBulk) Save(ctx context.Context) ([]*User, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/examples/traversal/ent/client.go b/examples/traversal/ent/client.go index 5f366b5fb2..0be5822239 100644 --- a/examples/traversal/ent/client.go +++ b/examples/traversal/ent/client.go @@ -157,7 +157,7 @@ func (c *GroupClient) Use(hooks ...Hook) { c.hooks.Group = append(c.hooks.Group, hooks...) } -// Create returns a create builder for Group. +// Create returns a builder for creating a Group entity. func (c *GroupClient) Create() *GroupCreate { mutation := newGroupMutation(c.config, OpCreate) return &GroupCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -192,12 +192,12 @@ func (c *GroupClient) Delete() *GroupDelete { return &GroupDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *GroupClient) DeleteOne(gr *Group) *GroupDeleteOne { return c.DeleteOneID(gr.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *GroupClient) DeleteOneID(id int) *GroupDeleteOne { builder := c.Delete().Where(group.ID(id)) builder.mutation.id = &id @@ -279,7 +279,7 @@ func (c *PetClient) Use(hooks ...Hook) { c.hooks.Pet = append(c.hooks.Pet, hooks...) } -// Create returns a create builder for Pet. +// Create returns a builder for creating a Pet entity. func (c *PetClient) Create() *PetCreate { mutation := newPetMutation(c.config, OpCreate) return &PetCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -314,12 +314,12 @@ func (c *PetClient) Delete() *PetDelete { return &PetDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *PetClient) DeleteOne(pe *Pet) *PetDeleteOne { return c.DeleteOneID(pe.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *PetClient) DeleteOneID(id int) *PetDeleteOne { builder := c.Delete().Where(pet.ID(id)) builder.mutation.id = &id @@ -401,7 +401,7 @@ func (c *UserClient) Use(hooks ...Hook) { c.hooks.User = append(c.hooks.User, hooks...) } -// Create returns a create builder for User. +// Create returns a builder for creating a User entity. func (c *UserClient) Create() *UserCreate { mutation := newUserMutation(c.config, OpCreate) return &UserCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -436,12 +436,12 @@ func (c *UserClient) Delete() *UserDelete { return &UserDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *UserClient) DeleteOne(u *User) *UserDeleteOne { return c.DeleteOneID(u.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *UserClient) DeleteOneID(id int) *UserDeleteOne { builder := c.Delete().Where(user.ID(id)) builder.mutation.id = &id diff --git a/examples/traversal/ent/group.go b/examples/traversal/ent/group.go index f463de3b66..4abaf1f6e0 100644 --- a/examples/traversal/ent/group.go +++ b/examples/traversal/ent/group.go @@ -144,8 +144,8 @@ func (gr *Group) Unwrap() *Group { func (gr *Group) String() string { var builder strings.Builder builder.WriteString("Group(") - builder.WriteString(fmt.Sprintf("id=%v", gr.ID)) - builder.WriteString(", name=") + builder.WriteString(fmt.Sprintf("id=%v, ", gr.ID)) + builder.WriteString("name=") builder.WriteString(gr.Name) builder.WriteByte(')') return builder.String() diff --git a/examples/traversal/ent/group_create.go b/examples/traversal/ent/group_create.go index cd1eea431d..bff10988a8 100644 --- a/examples/traversal/ent/group_create.go +++ b/examples/traversal/ent/group_create.go @@ -260,11 +260,11 @@ func (gcb *GroupCreateBulk) Save(ctx context.Context) ([]*Group, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/examples/traversal/ent/pet.go b/examples/traversal/ent/pet.go index 311335e288..b8cb903f39 100644 --- a/examples/traversal/ent/pet.go +++ b/examples/traversal/ent/pet.go @@ -144,8 +144,8 @@ func (pe *Pet) Unwrap() *Pet { func (pe *Pet) String() string { var builder strings.Builder builder.WriteString("Pet(") - builder.WriteString(fmt.Sprintf("id=%v", pe.ID)) - builder.WriteString(", name=") + builder.WriteString(fmt.Sprintf("id=%v, ", pe.ID)) + builder.WriteString("name=") builder.WriteString(pe.Name) builder.WriteByte(')') return builder.String() diff --git a/examples/traversal/ent/pet_create.go b/examples/traversal/ent/pet_create.go index d9dddf1b98..98fde5df6a 100644 --- a/examples/traversal/ent/pet_create.go +++ b/examples/traversal/ent/pet_create.go @@ -260,11 +260,11 @@ func (pcb *PetCreateBulk) Save(ctx context.Context) ([]*Pet, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/examples/traversal/ent/user.go b/examples/traversal/ent/user.go index cdfd58be32..a9c1bc27ed 100644 --- a/examples/traversal/ent/user.go +++ b/examples/traversal/ent/user.go @@ -168,10 +168,11 @@ func (u *User) Unwrap() *User { func (u *User) String() string { var builder strings.Builder builder.WriteString("User(") - builder.WriteString(fmt.Sprintf("id=%v", u.ID)) - builder.WriteString(", age=") + builder.WriteString(fmt.Sprintf("id=%v, ", u.ID)) + builder.WriteString("age=") builder.WriteString(fmt.Sprintf("%v", u.Age)) - builder.WriteString(", name=") + builder.WriteString(", ") + builder.WriteString("name=") builder.WriteString(u.Name) builder.WriteByte(')') return builder.String() diff --git a/examples/traversal/ent/user_create.go b/examples/traversal/ent/user_create.go index b8426b14f8..759b1cf5a6 100644 --- a/examples/traversal/ent/user_create.go +++ b/examples/traversal/ent/user_create.go @@ -341,11 +341,11 @@ func (ucb *UserCreateBulk) Save(ctx context.Context) ([]*User, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/examples/version/ent/client.go b/examples/version/ent/client.go index 1c0ae6ef07..e8554896c3 100644 --- a/examples/version/ent/client.go +++ b/examples/version/ent/client.go @@ -142,7 +142,7 @@ func (c *UserClient) Use(hooks ...Hook) { c.hooks.User = append(c.hooks.User, hooks...) } -// Create returns a create builder for User. +// Create returns a builder for creating a User entity. func (c *UserClient) Create() *UserCreate { mutation := newUserMutation(c.config, OpCreate) return &UserCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -177,12 +177,12 @@ func (c *UserClient) Delete() *UserDelete { return &UserDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *UserClient) DeleteOne(u *User) *UserDeleteOne { return c.DeleteOneID(u.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOne returns a builder for deleting the given entity by its id. func (c *UserClient) DeleteOneID(id int) *UserDeleteOne { builder := c.Delete().Where(user.ID(id)) builder.mutation.id = &id diff --git a/examples/version/ent/user.go b/examples/version/ent/user.go index b47f0392b3..f5bf5fe7f9 100644 --- a/examples/version/ent/user.go +++ b/examples/version/ent/user.go @@ -95,10 +95,11 @@ func (u *User) Unwrap() *User { func (u *User) String() string { var builder strings.Builder builder.WriteString("User(") - builder.WriteString(fmt.Sprintf("id=%v", u.ID)) - builder.WriteString(", version=") + builder.WriteString(fmt.Sprintf("id=%v, ", u.ID)) + builder.WriteString("version=") builder.WriteString(fmt.Sprintf("%v", u.Version)) - builder.WriteString(", status=") + builder.WriteString(", ") + builder.WriteString("status=") builder.WriteString(fmt.Sprintf("%v", u.Status)) builder.WriteByte(')') return builder.String() diff --git a/examples/version/ent/user_create.go b/examples/version/ent/user_create.go index 624a7d55ee..cc60ca4345 100644 --- a/examples/version/ent/user_create.go +++ b/examples/version/ent/user_create.go @@ -226,11 +226,11 @@ func (ucb *UserCreateBulk) Save(ctx context.Context) ([]*User, error) { return nil, err } mutation.id = &nodes[i].ID - mutation.done = true if specs[i].ID.Value != nil { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { diff --git a/schema/edge/edge.go b/schema/edge/edge.go index 5effa4c066..024ba10f0f 100644 --- a/schema/edge/edge.go +++ b/schema/edge/edge.go @@ -12,17 +12,18 @@ import ( // A Descriptor for edge configuration. type Descriptor struct { - Tag string // struct tag. - Type string // edge type. - Name string // edge name. - Field string // edge field name (e.g. foreign-key). - RefName string // ref name; inverse only. - Ref *Descriptor // edge reference; to/from of the same type. - Unique bool // unique edge. - Inverse bool // inverse edge. - Required bool // required on creation. - StorageKey *StorageKey // optional storage-key configuration. - Annotations []schema.Annotation // edge annotations. + Tag string // struct tag. + Type string // edge type. + Name string // edge name. + Field string // edge field name (e.g. foreign-key). + RefName string // ref name; inverse only. + Ref *Descriptor // edge reference; to/from of the same type. + Through *struct{ N, T string } // through type and name. + Unique bool // unique edge. + Inverse bool // inverse edge. + Required bool // required on creation. + StorageKey *StorageKey // optional storage-key configuration. + Annotations []schema.Annotation // edge annotations. } // To defines an association edge between two vertices. @@ -86,6 +87,16 @@ func (b *assocBuilder) Field(f string) *assocBuilder { return b } +// Through allows setting an "edge schema" to interact explicitly with M2M edges. +// +// edge.To("friends", User.Type). +// Through("friendships", Friendship.Type) +// +func (b *assocBuilder) Through(name string, t interface{}) *assocBuilder { + b.desc.Through = &struct{ N, T string }{N: name, T: typ(t)} + return b +} + // Comment used to put annotations on the schema. func (b *assocBuilder) Comment(string) *assocBuilder { return b @@ -173,6 +184,17 @@ func (b *inverseBuilder) Field(f string) *inverseBuilder { return b } +// Through allows setting an "edge schema" to interact explicitly with M2M edges. +// +// edge.From("liked_users", User.Type). +// Ref("liked_tweets"). +// Through("likes", TweetLike.Type) +// +func (b *inverseBuilder) Through(name string, t interface{}) *inverseBuilder { + b.desc.Through = &struct{ N, T string }{N: name, T: typ(t)} + return b +} + // Annotations adds a list of annotations to the edge object to be used by // codegen extensions. // diff --git a/schema/field/annotation.go b/schema/field/annotation.go index f8a0a0cfbd..8febb1de98 100644 --- a/schema/field/annotation.go +++ b/schema/field/annotation.go @@ -19,6 +19,30 @@ type Annotation struct { // } // StructTag map[string]string + + // ID defines a multi-field schema identifier. Note, + // the annotation is valid only for edge schemas. + // + // func (TweetLike) Annotations() []schema.Annotation { + // return []schema.Annotation{ + // field.ID("user_id", "tweet_id"), + // } + // } + // + ID []string +} + +// ID defines a multi-field schema identifier. Note, the +// annotation is valid only for edge schemas. +// +// func (TweetLike) Annotations() []schema.Annotation { +// return []schema.Annotation{ +// field.ID("user_id", "tweet_id"), +// } +// } +// +func ID(field string, fields ...string) *Annotation { + return &Annotation{ID: append([]string{field}, fields...)} } // Name describes the annotation name. @@ -45,10 +69,13 @@ func (a Annotation) Merge(other schema.Annotation) schema.Annotation { } a.StructTag[k] = v } + if len(ant.ID) > 0 { + a.ID = ant.ID + } return a } -var ( - _ schema.Annotation = (*Annotation)(nil) - _ schema.Merger = (*Annotation)(nil) -) +var _ interface { + schema.Annotation + schema.Merger +} = (*Annotation)(nil)