Working with Edges

Edges enable us to express the relationship between different entities in our ent application. Let’s see how they work together with generated gRPC services.

Let’s start by adding a new entity, Category and create edges relating our User type to it:

  1. package schema
  2. import (
  3. "entgo.io/contrib/entproto"
  4. "entgo.io/ent"
  5. "entgo.io/ent/schema"
  6. "entgo.io/ent/schema/edge"
  7. "entgo.io/ent/schema/field"
  8. )
  9. type Category struct {
  10. ent.Schema
  11. }
  12. func (Category) Fields() []ent.Field {
  13. return []ent.Field{
  14. field.String("name").
  15. Annotations(entproto.Field(2)),
  16. }
  17. }
  18. func (Category) Annotations() []schema.Annotation {
  19. return []schema.Annotation{
  20. entproto.Message(),
  21. }
  22. }
  23. func (Category) Edges() []ent.Edge {
  24. return []ent.Edge{
  25. edge.To("admin", User.Type).
  26. Unique().
  27. Annotations(entproto.Field(3)),
  28. }
  29. }

Creating the inverse relation on the User:

  1. // Edges of the User.
  2. func (User) Edges() []ent.Edge {
  3. return []ent.Edge{
  4. edge.From("administered", Category.Type).
  5. Ref("admin").
  6. Annotations(entproto.Field(5)),
  7. }
  8. }

Notice a few things:

  • Our edges also receive an entproto.Field annotation. We will see why in a minute.
  • We created a one-to-many relation ship where a Group has a single admin, and a User can administer multiple groups.

Re-generating the project with go generate ./..., notice the changes to the .proto file:

  1. message Category {
  2. int32 id = 1;
  3. string name = 2;
  4. User admin = 3;
  5. }
  6. message User {
  7. int32 id = 1;
  8. string name = 2;
  9. string email_address = 3;
  10. google.protobuf.StringValue alias = 4;
  11. repeated Category administered = 5;
  12. }

Observe the following changes:

  • A new message, Category was created. This message has a field named admin corresponding to the admin edge on the Category schema. It is a non-repeated field because we set the edge to be .Unique(). It’s field number is 3, corresponding to the entproto.Field annotation on the edge definition.
  • A new field administered was added to the User message definition. It is a repeated field, correspending to the fact that we did not mark the edge as Unique in this direction. It’s field number is 5, corresponding to the entproto.Field annotation on the edge.

Creating Entities with their Edges

Let’s demonstrate how to create an entity with it’s edges by writing a test:

  1. package main
  2. import (
  3. "context"
  4. "testing"
  5. _ "github.com/mattn/go-sqlite3"
  6. "github.com/rotemtam/ent-grpc-example/ent/category"
  7. "github.com/rotemtam/ent-grpc-example/ent/enttest"
  8. "github.com/rotemtam/ent-grpc-example/ent/proto/entpb"
  9. "github.com/rotemtam/ent-grpc-example/ent/user"
  10. )
  11. func TestServiceWithEdges(t *testing.T) {
  12. // start by initializing an ent client connected to an in memory sqlite instance
  13. ctx := context.Background()
  14. client := enttest.Open(t, "sqlite3", "file:ent?mode=memory&cache=shared&_fk=1")
  15. defer client.Close()
  16. // next, initialize the UserService. Notice we won't be opening an actual port and
  17. // creating a gRPC server and instead we are just calling the library code directly.
  18. svc := entpb.NewUserService(client)
  19. // next, we create a category directly using the ent client.
  20. // Notice we are initializing it with no relation to a User.
  21. cat := client.Category.Create().SetName("cat_1").SaveX(ctx)
  22. // next, we invoke the User service's `Create` method. Notice we are
  23. // passing a list of entpb.Category instances with only the ID set.
  24. create, err := svc.Create(ctx, &entpb.CreateUserRequest{
  25. User: &entpb.User{
  26. Name: "user",
  27. EmailAddress: "user@service.code",
  28. Administered: []*entpb.Category{
  29. {Id: int32(cat.ID)},
  30. },
  31. },
  32. })
  33. if err != nil {
  34. t.Fatal("failed creating user using UserService", err)
  35. }
  36. // to verify everything worked correctly, we query the category table to check
  37. // we have exactly one category which is administered by the created user.
  38. count, err := client.Category.
  39. Query().
  40. Where(
  41. category.HasAdminWith(
  42. user.ID(int(create.Id)),
  43. ),
  44. ).
  45. Count(ctx)
  46. if err != nil {
  47. t.Fatal("failed counting categories admin by created user", err)
  48. }
  49. if count != 1 {
  50. t.Fatal("expected exactly one group to managed by the created user")
  51. }
  52. }

To create the edge from the created User to the existing Category we do not need to populate the entire Category object. Instead we only populate the Id field. This is picked up by the generated service code:

  1. // Create implements UserServiceServer.Create
  2. func (svc *UserService) Create(ctx context.Context, req *CreateUserRequest) (*User, error) {
  3. user := req.GetUser()
  4. // truncated ...
  5. for _, item := range user.GetAdministered() {
  6. m.AddAdministeredIDs(int(item.GetId()))
  7. }
  8. res, err := m.Save(ctx)
  9. // truncated ...
  10. }

Retrieving Edge IDs for Entities

We have seen how to create relations between entities, but how do we retrieve that data from the generated gRPC service?

Consider this example test:

  1. func TestGet(t *testing.T) {
  2. // start by initializing an ent client connected to an in memory sqlite instance
  3. ctx := context.Background()
  4. client := enttest.Open(t, "sqlite3", "file:ent?mode=memory&cache=shared&_fk=1")
  5. defer client.Close()
  6. // next, initialize the UserService. Notice we won't be opening an actual port and
  7. // creating a gRPC server and instead we are just calling the library code directly.
  8. svc := entpb.NewUserService(client)
  9. // next, create a user, a category and set that user to be the admin of the category
  10. user := client.User.Create().
  11. SetName("rotemtam").
  12. SetEmailAddress("r@entgo.io").
  13. SaveX(ctx)
  14. client.Category.Create().
  15. SetName("category").
  16. SetAdmin(user).
  17. SaveX(ctx)
  18. // next, retrieve the user without edge information
  19. get, err := svc.Get(ctx, &entpb.GetUserRequest{
  20. Id: int32(user.ID),
  21. })
  22. if err != nil {
  23. t.Fatal("failed retrieving the created user", err)
  24. }
  25. if len(get.Administered) != 0 {
  26. t.Fatal("by default edge information is not supposed to be retrieved")
  27. }
  28. // next, retrieve the user *WITH* edge information
  29. get, err = svc.Get(ctx, &entpb.GetUserRequest{
  30. Id: int32(user.ID),
  31. View: entpb.GetUserRequest_WITH_EDGE_IDS,
  32. })
  33. if err != nil {
  34. t.Fatal("failed retrieving the created user", err)
  35. }
  36. if len(get.Administered) != 1 {
  37. t.Fatal("using WITH_EDGE_IDS edges should be returned")
  38. }
  39. }

As you can see in the test, by default, edge information is not returned by the Get method of the service. This is done deliberately because the amount of entities related to an entity is unbound. To allow the caller of to specify whether or not to return the edge information or not, the generated service adheres to AIP-157 (Partial Responses). In short, the GetUserRequest message includes an enum named View:

  1. message GetUserRequest {
  2. int32 id = 1;
  3. View view = 2;
  4. enum View {
  5. VIEW_UNSPECIFIED = 0;
  6. BASIC = 1;
  7. WITH_EDGE_IDS = 2;
  8. }
  9. }

Consider the generated code for the Get method:

  1. // Get implements UserServiceServer.Get
  2. func (svc *UserService) Get(ctx context.Context, req *GetUserRequest) (*User, error) {
  3. // .. truncated ..
  4. switch req.GetView() {
  5. case GetUserRequest_VIEW_UNSPECIFIED, GetUserRequest_BASIC:
  6. get, err = svc.client.User.Get(ctx, int(req.GetId()))
  7. case GetUserRequest_WITH_EDGE_IDS:
  8. get, err = svc.client.User.Query().
  9. Where(user.ID(int(req.GetId()))).
  10. WithAdministered(func(query *ent.CategoryQuery) {
  11. query.Select(category.FieldID)
  12. }).
  13. Only(ctx)
  14. default:
  15. return nil, status.Errorf(codes.InvalidArgument, "invalid argument: unknown view")
  16. }
  17. // .. truncated ..
  18. }

By default, client.User.Get is invoked, which does not return any edge ID information, but if WITH_EDGE_IDS is passed, the endpoint will retrieve the ID field for any Category related to the user via the administered edge.