Nullable columns and defaults
A plain field can't hold NULL, so ant writes a zero value as it is. Use a pointer or sql.Null[T] for a nullable column. The exception is a field tagged default.
Allow NULL in a column
type Profile struct {
ID int64
Bio *string
Age sql.Null[int64]
Website string
}
profile := &Profile{
Bio: new("Gopher"), // Go 1.26's new(expr)
Age: sql.Null[int64]{V: 30, Valid: true},
}
A pointer to an empty string is an empty string, not NULL.
Reading NULL into a plain field is an error. If a column holds NULL, make the field a pointer or sql.Null. For a custom type, use a pointer to the type.
Querying for NULL
ant.Eq with nil becomes IS NULL, and a pointer value compares what it points to.
noBio, err := db.Users.Where(ant.Eq(&Users.Bio, nil)).All(ctx)
// SELECT ... FROM "users" WHERE "users"."bio" IS NULL
same, err := db.Users.Where(ant.IsNull(&Users.Bio)).All(ctx)
// SELECT ... FROM "users" WHERE "users"."bio" IS NULL
hasBio, err := db.Users.Where(ant.IsNotNull(&Users.Bio)).All(ctx)
// SELECT ... FROM "users" WHERE "users"."bio" IS NOT NULL
gophers, err := db.Users.Where(ant.Eq(&Users.Bio, new("Gopher"))).All(ctx)
// SELECT ... FROM "users" WHERE "users"."bio" = $1
In and NotIn treat a nil among their values the same way. See conditions.
Set a column to NULL
nil in ant.Set writes NULL.
_, err := db.Users.Where(ant.Eq(&Users.ID, id)).Update(ctx, ant.Set(&Users.Bio, nil))
// UPDATE "users" SET "bio" = $1, "updated_at" = $2 WHERE "users"."id" = $3
// -- $1 = NULL
Database defaults
ant:"default=expr" declares the column's default, and a zero value in the field means "use it". Insert leaves the column out when the field is zero and copies the database's value back onto the struct.
type Account struct {
ID int64
Status string `ant:"default='new'"`
}
account := &Account{}
err := db.Accounts.Insert(ctx, account)
// INSERT INTO "accounts" DEFAULT VALUES RETURNING "id", "status"
fmt.Println(account.Status) // "new"
err = db.Accounts.Insert(ctx, &Account{Status: "vip"})
// INSERT INTO "accounts" ("status") VALUES ($1) RETURNING "id"
The expression is also the column's DEFAULT in migrations. It can instead be set in Configure, leaving the tag bare:
func (Post) Configure(b *ant.ModelBuilder[Post]) {
b.Column(&Posts.Title).Default("'Untitled'")
}
A bare ant:"default" works at run time, but EnsureCreated and migrations refuse it with ErrBadSchema because the column has no default.
Put a default only on a field whose zero means nothing. With Floor float64 and a default of -100.00, a real 0.00 becomes -100.00.
See it tested: tests/features/model_definition/nullable_test.go