Annotations

Schema annotations allow attaching metadata to schema objects like fields and edges and inject them to external templates. An annotation must be a Go type that is serializable to JSON raw value (e.g. struct, map or slice) and implement the Annotation interface.

The builtin annotations allow configuring the different storage drivers (like SQL) and control the code generation output.

Custom Table Name

A custom table name can be provided for types using the entsql annotation as follows:

  1. package schema
  2. import (
  3. "entgo.io/ent"
  4. "entgo.io/ent/dialect/entsql"
  5. "entgo.io/ent/schema"
  6. "entgo.io/ent/schema/field"
  7. )
  8. // User holds the schema definition for the User entity.
  9. type User struct {
  10. ent.Schema
  11. }
  12. // Annotations of the User.
  13. func (User) Annotations() []schema.Annotation {
  14. return []schema.Annotation{
  15. entsql.Annotation{Table: "Users"},
  16. }
  17. }
  18. // Fields of the User.
  19. func (User) Fields() []ent.Field {
  20. return []ent.Field{
  21. field.Int("age"),
  22. field.String("name"),
  23. }
  24. }

Foreign Keys Configuration

Ent allows to customize the foreign key creation and provide a referential action for the ON DELETE clause:

  1. package schema
  2. import (
  3. "entgo.io/ent"
  4. "entgo.io/ent/dialect/entsql"
  5. "entgo.io/ent/schema/edge"
  6. "entgo.io/ent/schema/field"
  7. )
  8. // User holds the schema definition for the User entity.
  9. type User struct {
  10. ent.Schema
  11. }
  12. // Fields of the User.
  13. func (User) Fields() []ent.Field {
  14. return []ent.Field{
  15. field.String("name").
  16. Default("Unknown"),
  17. }
  18. }
  19. // Edges of the User.
  20. func (User) Edges() []ent.Edge {
  21. return []ent.Edge{
  22. edge.To("posts", Post.Type).
  23. Annotations(entsql.Annotation{
  24. OnDelete: entsql.Cascade,
  25. }),
  26. }
  27. }

The example above configures the foreign key to cascade the deletion of rows in the parent table to the matching rows in the child table.