Feature Flags

The framework provides a collection of code-generation features that be added or removed using flags.

Usage

Feature flags can be provided either by CLI flags or as arguments to the gen package.

CLI

  1. go run -mod=mod entgo.io/ent/cmd/ent generate --feature privacy,entql ./ent/schema

Go

  1. // +build ignore
  2. package main
  3. import (
  4. "log"
  5. "text/template"
  6. "entgo.io/ent/entc"
  7. "entgo.io/ent/entc/gen"
  8. )
  9. func main() {
  10. err := entc.Generate("./schema", &gen.Config{
  11. Features: []gen.Feature{
  12. gen.FeaturePrivacy,
  13. gen.FeatureEntQL,
  14. },
  15. Templates: []*gen.Template{
  16. gen.MustParse(gen.NewTemplate("static").
  17. Funcs(template.FuncMap{"title": strings.ToTitle}).
  18. ParseFiles("template/static.tmpl")),
  19. },
  20. })
  21. if err != nil {
  22. log.Fatalf("running ent codegen: %v", err)
  23. }
  24. }

List of Features

Auto-Solve Merge Conflicts

The schema/snapshot option tells entc (ent codegen) to store a snapshot of the latest schema in an internal package, and use it to automatically solve merge conflicts when user’s schema can’t be built.

This option can be added to a project using the --feature schema/snapshot flag, but please see ent/ent/issues/852 to get more context about it.

Privacy Layer

The privacy layer allows configuring privacy policy for queries and mutations of entities in the database.

This option can be added to a project using the --feature privacy flag, and you can learn more about in the privacy documentation.

EntQL Filtering

The entql option provides a generic and dynamic filtering capability at runtime for the different query builders.

This option can be added to a project using the --feature entql flag, and you can learn more about in the privacy documentation.

Named Edges

The namedges option provides an API for preloading edges with custom names.

This option can be added to a project using the --feature namedges flag, and you can learn more about in the Eager Loading documentation.

Bidirectional Edge Refs

The bidiedges option guides Ent to set two-way references when eager-loading (O2M/O2O) edges.

This option can be added to a project using the --feature bidiedges flag.

Feature Flags - 图1note

Users that use the standard encoding/json.MarshalJSON should detach the circular references before calling json.Marshal.

Schema Config

The sql/schemaconfig option lets you pass alternate SQL database names to models. This is useful when your models don’t all live under one database and are spread out across different schemas.

This option can be added to a project using the --feature sql/schemaconfig flag. Once you generate the code, you can now use a new option as such:

  1. c, err := ent.Open(dialect, conn, ent.AlternateSchema(ent.SchemaConfig{
  2. User: "usersdb",
  3. Car: "carsdb",
  4. }))
  5. c.User.Query().All(ctx) // SELECT * FROM `usersdb`.`users`
  6. c.Car.Query().All(ctx) // SELECT * FROM `carsdb`.`cars`

Row-level Locks

The sql/lock option lets configure row-level locking using the SQL SELECT ... FOR {UPDATE | SHARE} syntax.

This option can be added to a project using the --feature sql/lock flag.

  1. tx, err := client.Tx(ctx)
  2. if err != nil {
  3. log.Fatal(err)
  4. }
  5. tx.Pet.Query().
  6. Where(pet.Name(name)).
  7. ForUpdate().
  8. Only(ctx)
  9. tx.Pet.Query().
  10. Where(pet.ID(id)).
  11. ForShare(
  12. sql.WithLockTables(pet.Table),
  13. sql.WithLockAction(sql.NoWait),
  14. ).
  15. Only(ctx)

Custom SQL Modifiers

The sql/modifier option lets add custom SQL modifiers to the builders and mutate the statements before they are executed.

This option can be added to a project using the --feature sql/modifier flag.

Modify Example 1

  1. client.Pet.
  2. Query().
  3. Modify(func(s *sql.Selector) {
  4. s.Select("SUM(LENGTH(name))")
  5. }).
  6. IntX(ctx)

The above code will produce the following SQL query:

  1. SELECT SUM(LENGTH(name)) FROM `pet`

Select and Scan Dynamic Values

If you work with SQL modifiers and need to scan dynamic values not present in your Ent schema definition, such as aggregation or custom ordering, you can apply AppendSelect/AppendSelectAs to the sql.Selector. You can later access their values using the Value method defined on each entity:

  1. const as = "name_length"
  2. // Query the entity with the dynamic value.
  3. p := client.Pet.Query().
  4. Modify(func(s *sql.Selector) {
  5. s.AppendSelectAs("LENGTH(name)", as)
  6. }).
  7. FirstX(ctx)
  8. // Read the value from the entity.
  9. n, err := p.Value(as)
  10. if err != nil {
  11. log.Fatal(err)
  12. }
  13. fmt.Println("Name length: %d == %d", n, len(p.Name))

Modify Example 2

  1. var p1 []struct {
  2. ent.Pet
  3. NameLength int `sql:"length"`
  4. }
  5. client.Pet.Query().
  6. Order(ent.Asc(pet.FieldID)).
  7. Modify(func(s *sql.Selector) {
  8. s.AppendSelect("LENGTH(name)")
  9. }).
  10. ScanX(ctx, &p1)

The above code will produce the following SQL query:

  1. SELECT `pet`.*, LENGTH(name) FROM `pet` ORDER BY `pet`.`id` ASC

Modify Example 3

  1. var v []struct {
  2. Count int `json:"count"`
  3. Price int `json:"price"`
  4. CreatedAt time.Time `json:"created_at"`
  5. }
  6. client.User.
  7. Query().
  8. Where(
  9. user.CreatedAtGT(x),
  10. user.CreatedAtLT(y),
  11. ).
  12. Modify(func(s *sql.Selector) {
  13. s.Select(
  14. sql.As(sql.Count("*"), "count"),
  15. sql.As(sql.Sum("price"), "price"),
  16. sql.As("DATE(created_at)", "created_at"),
  17. ).
  18. GroupBy("DATE(created_at)").
  19. OrderBy(sql.Desc("DATE(created_at)"))
  20. }).
  21. ScanX(ctx, &v)

The above code will produce the following SQL query:

  1. SELECT
  2. COUNT(*) AS `count`,
  3. SUM(`price`) AS `price`,
  4. DATE(created_at) AS `created_at`
  5. FROM
  6. `users`
  7. WHERE
  8. `created_at` > x AND `created_at` < y
  9. GROUP BY
  10. DATE(created_at)
  11. ORDER BY
  12. DATE(created_at) DESC

Modify Example 4

  1. var gs []struct {
  2. ent.Group
  3. UsersCount int `sql:"users_count"`
  4. }
  5. client.Group.Query().
  6. Order(ent.Asc(group.FieldID)).
  7. Modify(func(s *sql.Selector) {
  8. t := sql.Table(group.UsersTable)
  9. s.LeftJoin(t).
  10. On(
  11. s.C(group.FieldID),
  12. t.C(group.UsersPrimaryKey[1]),
  13. ).
  14. // Append the "users_count" column to the selected columns.
  15. AppendSelect(
  16. sql.As(sql.Count(t.C(group.UsersPrimaryKey[1])), "users_count"),
  17. ).
  18. GroupBy(s.C(group.FieldID))
  19. }).
  20. ScanX(ctx, &gs)

The above code will produce the following SQL query:

  1. SELECT
  2. `groups`.*,
  3. COUNT(`t1`.`group_id`) AS `users_count`
  4. FROM
  5. `groups` LEFT JOIN `user_groups` AS `t1`
  6. ON
  7. `groups`.`id` = `t1`.`group_id`
  8. GROUP BY
  9. `groups`.`id`
  10. ORDER BY
  11. `groups`.`id` ASC

Modify Example 5

  1. client.User.Update().
  2. Modify(func(s *sql.UpdateBuilder) {
  3. s.Set(user.FieldName, sql.Expr(fmt.Sprintf("UPPER(%s)", user.FieldName)))
  4. }).
  5. ExecX(ctx)

The above code will produce the following SQL query:

  1. UPDATE `users` SET `name` = UPPER(`name`)

Modify Example 6

  1. client.User.Update().
  2. Modify(func(u *sql.UpdateBuilder) {
  3. u.Set(user.FieldID, sql.ExprFunc(func(b *sql.Builder) {
  4. b.Ident(user.FieldID).WriteOp(sql.OpAdd).Arg(1)
  5. }))
  6. u.OrderBy(sql.Desc(user.FieldID))
  7. }).
  8. ExecX(ctx)

The above code will produce the following SQL query:

  1. UPDATE `users` SET `id` = `id` + 1 ORDER BY `id` DESC

Modify Example 7

Append elements to the values array in a JSON column:

  1. client.User.Update().
  2. Modify(func(u *sql.UpdateBuilder) {
  3. sqljson.Append(u, user.FieldTags, []string{"tag1", "tag2"}, sqljson.Path("values"))
  4. }).
  5. ExecX(ctx)

The above code will produce the following SQL query:

  1. UPDATE `users` SET `tags` = CASE
  2. WHEN (JSON_TYPE(JSON_EXTRACT(`tags`, '$.values')) IS NULL OR JSON_TYPE(JSON_EXTRACT(`tags`, '$.values')) = 'NULL')
  3. THEN JSON_SET(`tags`, '$.values', JSON_ARRAY(?, ?))
  4. ELSE JSON_ARRAY_APPEND(`tags`, '$.values', ?, '$.values', ?) END
  5. WHERE `id` = ?

SQL Raw API

The sql/execquery option allows executing statements using the ExecContext/QueryContext methods of the underlying driver. For full documentation, see: DB.ExecContext, and DB.QueryContext.

  1. // From ent.Client.
  2. if _, err := client.ExecContext(ctx, "TRUNCATE t1"); err != nil {
  3. return err
  4. }
  5. // From ent.Tx.
  6. tx, err := client.Tx(ctx)
  7. if err != nil {
  8. return err
  9. }
  10. if err := tx.User.Create().Exec(ctx); err != nil {
  11. return err
  12. }
  13. if _, err := tx.ExecContext("SAVEPOINT user_created"); err != nil {
  14. return err
  15. }
  16. // ...

Feature Flags - 图2Note

Statements executed using ExecContext/QueryContext do not go through Ent, and may skip fundamental layers in your application such as hooks, privacy (authorization), and validators.

Upsert

The sql/upsert option lets configure upsert and bulk-upsert logic using the SQL ON CONFLICT / ON DUPLICATE KEY syntax. For full documentation, go to the Upsert API.

This option can be added to a project using the --feature sql/upsert flag.

  1. // Use the new values that were set on create.
  2. id, err := client.User.
  3. Create().
  4. SetAge(30).
  5. SetName("Ariel").
  6. OnConflict().
  7. UpdateNewValues().
  8. ID(ctx)
  9. // In PostgreSQL, the conflict target is required.
  10. err := client.User.
  11. Create().
  12. SetAge(30).
  13. SetName("Ariel").
  14. OnConflictColumns(user.FieldName).
  15. UpdateNewValues().
  16. Exec(ctx)
  17. // Bulk upsert is also supported.
  18. client.User.
  19. CreateBulk(builders...).
  20. OnConflict(
  21. sql.ConflictWhere(...),
  22. sql.UpdateWhere(...),
  23. ).
  24. UpdateNewValues().
  25. Exec(ctx)
  26. // INSERT INTO "users" (...) VALUES ... ON CONFLICT WHERE ... DO UPDATE SET ... WHERE ...