Predicates

Field Predicates

  • Bool:
    • =, !=
  • Numeric:
    • =, !=, >, <, >=, <=,
    • IN, NOT IN
  • Time:
    • =, !=, >, <, >=, <=
    • IN, NOT IN
  • String:
    • =, !=, >, <, >=, <=
    • IN, NOT IN
    • Contains, HasPrefix, HasSuffix
    • ContainsFold, EqualFold (SQL specific)
  • JSON
    • =, !=
    • =, !=, >, <, >=, <= on nested values (JSON path).
    • Contains on nested values (JSON path).
    • HasKey, Len<P>
    • null checks for nested values (JSON path).
  • Optional fields:
    • IsNil, NotNil

Edge Predicates

  • HasEdge. For example, for edge named owner of type Pet, use:

    1. client.Pet.
    2. Query().
    3. Where(pet.HasOwner()).
    4. All(ctx)
  • HasEdgeWith. Add list of predicates for edge predicate.

    1. client.Pet.
    2. Query().
    3. Where(pet.HasOwnerWith(user.Name("a8m"))).
    4. All(ctx)

Negation (NOT)

  1. client.Pet.
  2. Query().
  3. Where(pet.Not(pet.NameHasPrefix("Ari"))).
  4. All(ctx)

Disjunction (OR)

  1. client.Pet.
  2. Query().
  3. Where(
  4. pet.Or(
  5. pet.HasOwner(),
  6. pet.Not(pet.HasFriends()),
  7. )
  8. ).
  9. All(ctx)

Conjunction (AND)

  1. client.Pet.
  2. Query().
  3. Where(
  4. pet.And(
  5. pet.HasOwner(),
  6. pet.Not(pet.HasFriends()),
  7. )
  8. ).
  9. All(ctx)

Custom Predicates

Custom predicates can be useful if you want to write your own dialect-specific logic or to control the executed queries.

Get all pets of users 1, 2 and 3

  1. pets := client.Pet.
  2. Query().
  3. Where(func(s *sql.Selector) {
  4. s.Where(sql.InInts(pet.FieldOwnerID, 1, 2, 3))
  5. }).
  6. AllX(ctx)

The above code will produce the following SQL query:

  1. SELECT DISTINCT `pets`.`id`, `pets`.`owner_id` FROM `pets` WHERE `owner_id` IN (1, 2, 3)

Count the number of users whose JSON field named URL contains the Scheme key

  1. count := client.User.
  2. Query().
  3. Where(func(s *sql.Selector) {
  4. s.Where(sqljson.HasKey(user.FieldURL, sqljson.Path("Scheme")))
  5. }).
  6. CountX(ctx)

The above code will produce the following SQL query:

  1. -- PostgreSQL
  2. SELECT COUNT(DISTINCT "users"."id") FROM "users" WHERE "url"->'Scheme' IS NOT NULL
  3. -- SQLite and MySQL
  4. SELECT COUNT(DISTINCT `users`.`id`) FROM `users` WHERE JSON_EXTRACT(`url`, "$.Scheme") IS NOT NULL

Get all users with a "Tesla" car

Consider an ent query such as:

  1. users := client.User.Query().
  2. Where(user.HasCarWith(car.Model("Tesla"))).
  3. AllX(ctx)

This query can be rephrased in 3 different forms: IN, EXISTS and JOIN.

  1. // `IN` version.
  2. users := client.User.Query().
  3. Where(func(s *sql.Selector) {
  4. t := sql.Table(car.Table)
  5. s.Where(
  6. sql.In(
  7. s.C(user.FieldID),
  8. sql.Select(t.C(user.FieldID)).From(t).Where(sql.EQ(t.C(car.FieldModel), "Tesla")),
  9. ),
  10. )
  11. }).
  12. AllX(ctx)
  13. // `JOIN` version.
  14. users := client.User.Query().
  15. Where(func(s *sql.Selector) {
  16. t := sql.Table(car.Table)
  17. s.Join(t).On(s.C(user.FieldID), t.C(car.FieldOwnerID))
  18. s.Where(sql.EQ(t.C(car.FieldModel), "Tesla"))
  19. }).
  20. AllX(ctx)
  21. // `EXISTS` version.
  22. users := client.User.Query().
  23. Where(func(s *sql.Selector) {
  24. t := sql.Table(car.Table)
  25. p := sql.And(
  26. sql.EQ(t.C(car.FieldModel), "Tesla"),
  27. sql.ColumnsEQ(s.C(user.FieldID), t.C(car.FieldOwnerID)),
  28. )
  29. s.Where(sql.Exists(sql.Select().From(t).Where(p)))
  30. }).
  31. AllX(ctx)

The above code will produce the following SQL query:

  1. -- `IN` version.
  2. SELECT DISTINCT `users`.`id`, `users`.`age`, `users`.`name` FROM `users` WHERE `users`.`id` IN (SELECT `cars`.`id` FROM `cars` WHERE `cars`.`model` = 'Tesla')
  3. -- `JOIN` version.
  4. SELECT DISTINCT `users`.`id`, `users`.`age`, `users`.`name` FROM `users` JOIN `cars` ON `users`.`id` = `cars`.`owner_id` WHERE `cars`.`model` = 'Tesla'
  5. -- `EXISTS` version.
  6. SELECT DISTINCT `users`.`id`, `users`.`age`, `users`.`name` FROM `users` WHERE EXISTS (SELECT * FROM `cars` WHERE `cars`.`model` = 'Tesla' AND `users`.`id` = `cars`.`owner_id`)

Get all pets where pet name contains a specific pattern

The generated code provides the HasPrefix, HasSuffix, Contains, and ContainsFold predicates for pattern matching. However, in order to use the LIKE operator with a custom pattern, use the following example.

  1. pets := client.Pet.Query().
  2. Where(func(s *sql.Selector){
  3. s.Where(sql.Like(pet.Name,"_B%"))
  4. }).
  5. AllX(ctx)

The above code will produce the following SQL query:

  1. SELECT DISTINCT `pets`.`id`, `pets`.`owner_id`, `pets`.`name`, `pets`.`age`, `pets`.`species` FROM `pets` WHERE `name` LIKE '_B%'

Custom SQL functions

In order to use built-in SQL functions such as DATE(), use one of the following options:

  1. Pass a dialect-aware predicate function using the sql.P option:
  1. users := client.User.Query().
  2. Select(user.FieldID).
  3. Where(sql.P(func(b *sql.Builder) {
  4. b.WriteString("DATE(").Ident("last_login_at").WriteByte(')').WriteOp(OpGTE).Arg(value)
  5. })).
  6. AllX(ctx)

The above code will produce the following SQL query:

  1. SELECT `id` FROM `users` WHERE DATE(`last_login_at`) >= ?
  1. Inline a predicate expression using the ExprP() option:
  1. users := client.User.Query().
  2. Select(user.FieldID).
  3. Where(func(s *sql.Selector) {
  4. s.Where(sql.ExprP("DATE(last_login_at) >= ?", value))
  5. }).
  6. AllX(ctx)

The above code will produce the same SQL query:

  1. SELECT `id` FROM `users` WHERE DATE(`last_login_at`) >= ?

JSON predicates

JSON predicates are not generated by default as part of the code generation. However, ent provides an official package named sqljson for applying predicates on JSON columns using the custom predicates option.

Compare a JSON value

  1. sqljson.ValueEQ(user.FieldData, data)
  2. sqljson.ValueEQ(user.FieldURL, "https", sqljson.Path("Scheme"))
  3. sqljson.ValueNEQ(user.FieldData, content, sqljson.DotPath("attributes[1].body.content"))
  4. sqljson.ValueGTE(user.FieldData, status.StatusBadRequest, sqljson.Path("response", "status"))

Check for the presence of a JSON key

  1. sqljson.HasKey(user.FieldData, sqljson.Path("attributes", "[1]", "body"))
  2. sqljson.HasKey(user.FieldData, sqljson.DotPath("attributes[1].body"))

Note that, a key with the null literal as a value also matches this operation.

Check JSON null literals

  1. sqljson.ValueIsNull(user.FieldData)
  2. sqljson.ValueIsNull(user.FieldData, sqljson.Path("attributes"))
  3. sqljson.ValueIsNull(user.FieldData, sqljson.DotPath("attributes[1].body"))

Note that, the ValueIsNull returns true if the value is JSON null, but not database NULL.

Compare the length of a JSON array

  1. sqljson.LenEQ(user.FieldAttrs, 2)
  2. sql.Or(
  3. sqljson.LenGT(user.FieldData, 10, sqljson.Path("attributes")),
  4. sqljson.LenLT(user.FieldData, 20, sqljson.Path("attributes")),
  5. )

Check if a JSON value contains another value

  1. sqljson.ValueContains(user.FieldData, data)
  2. sqljson.ValueContains(user.FieldData, attrs, sqljson.Path("attributes"))
  3. sqljson.ValueContains(user.FieldData, code, sqljson.DotPath("attributes[0].status_code"))

Check if a JSON string value contains a given substring or has a given suffix or prefix

  1. sqljson.StringContains(user.FieldURL, "github", sqljson.Path("host"))
  2. sqljson.StringHasSuffix(user.FieldURL, ".com", sqljson.Path("host"))
  3. sqljson.StringHasPrefix(user.FieldData, "20", sqljson.DotPath("attributes[0].status_code"))

Check if a JSON value is equal to any of the values in a list

  1. sqljson.ValueIn(user.FieldURL, []any{"https", "ftp"}, sqljson.Path("Scheme"))
  2. sqljson.ValueNotIn(user.FieldURL, []any{"github", "gitlab"}, sqljson.Path("Host"))