Embedded structs and mixins
Share fields with an embedded struct
An anonymous embedded struct adds its fields to the model's columns. ant.Base works this way.
type Audit struct {
CreatedBy string
}
type Shop struct {
Audit
ID int64
Name string
}
shops gets a created_by column.
Group columns under a prefix
The embedded tag does the same for a named field. prefix keeps two groups of the same type apart.
type Address struct {
City string
Zip string
}
type Shop struct {
ID int64
Billing Address `ant:"embedded,prefix=billing_"`
Shipping Address `ant:"embedded,prefix=shipping_"`
}
var Shops = ant.Fields[Shop]()
oslo, err := db.Shops.Where(ant.Eq(&Shops.Shipping.City, "Oslo")).All(ctx)
// SELECT ... FROM "shops" WHERE "shops"."shipping_city" = $1
Tracking works per column, so changing one field writes one column:
session := ant.Session(db)
shop, err := session.Shops.Find(ctx, id)
shop.Billing.Zip = "9"
err = session.SaveChanges(ctx)
// UPDATE "shops" SET "billing_zip" = $1 WHERE "shops"."id" = $2
Embedded structs can nest.
Embed when the data is part of the row and always read with it. Use a relation when the data has its own rows, its own key, or is shared between rows.
The field must be a struct value
ant:"embedded" goes on a struct value. On a pointer, a scalar, or a struct that holds such a field, ant returns an error that names the field:
type Courier struct {
ID int64
Depot *Address `ant:"embedded,prefix=depot_"`
}
ant: embedded field Courier.Depot must be a struct value, got *Address
ant.Open returns it, as does every query, raw query and projection that uses the model, which would otherwise scan into only some of the fields. A pointer is refused because ant would have to decide whether a row of NULL columns means a nil pointer or a zero struct. For an optional group of columns, use pointer fields inside the struct:
type Address struct {
City *string
Zip *string
}
A nested field is named with its path: ant: embedded field Customer.Home.Depot must be a struct value, got *Address.
Mixins
A mixin is an embedded struct with a ConfigureMixin method. It works on columns by name, without knowing the embedding model.
type Created struct {
Created int64
}
func (Created) ConfigureMixin(m *ant.Mixin) {
m.Index("created").Name(m.Table() + "_created_idx")
m.Check(m.Table()+"_created_positive", "created >= 0")
}
type Event struct {
ID int64
Created
}
events gets events_created_idx and events_created_positive. m.Table() is the name of the embedding model's table, which keeps the names unique.
A mixin can add a global filter, as in multi-tenancy. A hook method on the mixin is promoted to every model that embeds it.
See it tested: tests/features/model_definition/embedded_test.go