Skip to main content

Field probes

A field pointer such as &Users.Age names the age column of User without a string. It is a *int, so the compiler knows the column's type.

Declare a probe​

Declare one probe per model, next to the model. It holds no data, and ant.Fields returns the same one every time.

These docs name a probe after its model in the plural, the way ant names the table: Users for User, Categories for Category. Two models never get the same name, and &Users.Age reads like the column users.age. It is a convention, not a rule. Any name works.

var (
Users = ant.Fields[User]()
Posts = ant.Fields[Post]()
)

adults, err := db.Users.Where(ant.Gt(&Users.Age, 18)).All(ctx)
// SELECT ... FROM "users" WHERE "users"."age" > $1

Type errors become compile errors​

Gt[V Ordered](field *V, v V) is generic, so the value must have the field's type.

db.Users.Where(ant.Gt(&Users.Age, "18"))
cannot use "18" (untyped string constant) as int value in argument to ant.Gt

A misspelled field or a column of the wrong kind for the operation is also a compile error.

db.Users.Where(ant.Eq(&Users.Nmae, "x"))
db.Users.Where(ant.Like(&Users.Age, "1%"))
db.Users.Include(&Users.Name)
Users.Nmae undefined (type *User has no field or method Nmae)
in call to ant.Like, V (type int) does not satisfy ~string
in call to db.Users.Include, type *string of &Users.Name does not match *[]R (cannot infer R)

Renaming a field in your editor renames it in every query.

Nested and promoted fields​

Field pointers follow promoted fields and embedded structs.

db.Users.OrderBy(&Users.CreatedAt) // promoted from ant.Base
// ... ORDER BY "users"."created_at"

db.Shops.Where(ant.Eq(&Shops.Shipping.City, "Oslo"))
// ... WHERE "shops"."shipping_city" = $1

Pass columns of different types​

Calls that take columns of different types, such as a composite key, take FieldRefs. ant.F turns a field pointer into one.

func (Grant) Configure(b *ant.ModelBuilder[Grant]) {
b.CompositeKey(ant.F(&Grants.UserID), ant.F(&Grants.Scope))
}

How a probe is resolved​

ant.Fields[User]() allocates one User, and &Users.Age is an address inside it. ant subtracts the probe's start address to get an offset, and walks the struct once with reflect to map offsets to fields.

An offset is not unique: &Users.Base and &Users.ID share an address because ID is the first field of Base, so ant matches on address and type.

Mistakes the compiler can't see​

A condition doesn't carry its model's type, so these compile and fail when the query runs. antvet flags them earlier.

age := 18

_, err := db.Users.Where(ant.Gt(&age, 18)).All(ctx)
errors.Is(err, ant.ErrNotProbe) // true: &age is not a probe

_, err = db.Posts.Where(ant.Gt(&Users.Age, 18)).All(ctx)
errors.Is(err, ant.ErrWrongModel) // true: &Users.Age belongs to User

_, err = db.Posts.Where(ant.IsNull(&Posts.User)).All(ctx)
errors.Is(err, ant.ErrNotColumn) // true: a relation is not a column