Shared tables and views
Several models in one table
Each type is a plain struct, and a discriminator column says which rows belong to which. Insert sets the discriminator, and each model's queries see only its own rows.
type Dog struct {
ID int64
Kind string
Name string
Barks *int
}
func (Dog) Configure(b *ant.ModelBuilder[Dog]) {
b.Table("animals")
b.Discriminator(&Dogs.Kind, "dog")
}
type Cat struct {
ID int64
Kind string
Name string
Lives *int
}
func (Cat) Configure(b *ant.ModelBuilder[Cat]) {
b.Table("animals")
b.Discriminator(&Cats.Kind, "cat")
}
var (
Dogs = ant.Fields[Dog]()
Cats = ant.Fields[Cat]()
)
err := db.Dogs.Insert(ctx, &Dog{Name: "Rex"})
// INSERT INTO "animals" ("kind", "name") VALUES ($1, $2) RETURNING "id" -- $1 = dog
dogs, err := db.Dogs.Where(ant.Eq(&Dogs.Name, "Rex")).All(ctx)
// SELECT ... FROM "animals" WHERE "animals"."name" = $1 AND "animals"."kind" = $2 -- $2 = dog
cats, err := db.Cats.Where(ant.Eq(&Cats.Name, "Rex")).All(ctx)
// SELECT ... FROM "animals" WHERE "animals"."name" = $1 AND "animals"."kind" = $2 -- $2 = cat
Migrations see one table. A column that only one model declares, such as barks, allows NULL.
Split one table into several models
Models can share a table without a discriminator, such as a small model for the common read and a full one for the rest.
type UserName struct {
ID int64
Name string
}
func (UserName) Configure(b *ant.ModelBuilder[UserName]) {
b.Table("users")
}
A table is shared only when you say so, with b.Table or b.Discriminator. Two models that reach one table by convention, such as billing.Account and auth.Account, are refused when the context opens, since each would read the other's rows.
To keep a separate table per type, embed a shared struct in each model.
Map a model to a view
b.View maps a model to a database view. It refuses every write with ant.ErrReadOnly. Create the view itself in migrations/code.
type ActiveUser struct {
ID int64
Name string
}
func (ActiveUser) Configure(b *ant.ModelBuilder[ActiveUser]) {
b.View("active_users")
}
A tracked row from a view can't be saved either: SaveChanges returns ant.ErrReadOnly.
Put a table in a schema
b.Schema places a table in a database schema. Migrations create the schema and qualify every name.
func (Invoice) Configure(b *ant.ModelBuilder[Invoice]) {
b.Schema("billing")
}
invoices, err := db.Invoices.All(ctx)
// SELECT ... FROM "billing"."invoices"
See it tested: tests/features/model_definition/inheritance_test.go