Keys
A field named ID is the primary key. The database generates an integer key and ant copies it back onto your struct.
Use ID as the key
type Ticket struct {
ID int64
Title string
}
ticket := &Ticket{Title: "One"}
err := db.Tickets.Insert(ctx, ticket)
// INSERT INTO "tickets" ("title") VALUES ($1) RETURNING "id"
fmt.Println(ticket.ID) // set by the database
found, err := db.Tickets.Find(ctx, ticket.ID)
// SELECT ... FROM "tickets" WHERE "tickets"."id" = $1 LIMIT $2
A zero integer key means "assign me one", the only place ant reads a zero as "not set" without a tag. A non-zero key is written as given, even on a generated column, so imported rows keep their IDs.
imported := &Ticket{ID: 500, Title: "Imported"}
err := db.Tickets.Insert(ctx, imported)
// INSERT INTO "tickets" ("id", "title") VALUES ($1, $2)
Use another column as the key
b.Key replaces the convention. An ID field on the same model then becomes an ordinary column.
type Country struct {
ID int64
Code string
}
func (Country) Configure(b *ant.ModelBuilder[Country]) {
b.Key(&Countries.Code)
}
var Countries = ant.Fields[Country]()
latvia, err := db.Countries.Find(ctx, "LV")
// SELECT ... FROM "countries" WHERE "countries"."code" = $1 LIMIT $2
Supply the key yourself
With NotGenerated, a zero key is a real value and is written as it is.
type Seat struct {
Number int
Row string
}
func (Seat) Configure(b *ant.ModelBuilder[Seat]) {
b.Key(&Seats.Number).NotGenerated()
}
var Seats = ant.Fields[Seat]()
err := db.Seats.Insert(ctx, &Seat{Number: 0, Row: "A"})
// INSERT INTO "seats" ("number", "row") VALUES ($1, $2) -- $1 = 0
String and UUID keys
The database generates only integer keys. A string or uuid.UUID key is yours to fill: set it, generate it in Go, or give the column a default. A named type works as a key and a plain string finds it.
type Slug string
type Page struct {
ID Slug
Title string
}
err := db.Pages.Insert(ctx, &Page{ID: "home", Title: "Home"})
// INSERT INTO "pages" ("id", "title") VALUES ($1, $2)
home, err := db.Pages.Find(ctx, "home")
An insert with the key at its zero value, an empty string or the zero uuid.UUID, is refused before anything is written, since every such row would get the same key and the second would fail as a duplicate:
err := db.Pages.Insert(ctx, &Page{Title: "Untitled"})
// ant: the key is zero and nothing generates it: Page.ID is the zero main.Slug, and nothing
// generates it: set it before the insert, generate it with ant.GenerateKey in Configure ...
errors.Is(err, ant.ErrZeroKey) // true
For a uuid.UUID from github.com/google/uuid, generate it in Go with ant.GenerateKey(b, &Docs.ID, ids.UUIDv7[uuid.UUID]). A database default or a BeforeInsert hook works too, and a hook runs before the check: see a UUID key on every model.
Generate the key in Go
ant.GenerateKey fills in a zero key before the insert and keeps a key you supply. If the insert fails, the generated key is cleared from the struct, so a retry makes a new one. It fills the key on every insert: Insert, InsertMany, Upsert and SaveChanges.
type Order struct {
ID uuid.UUID
Total int
}
func (Order) Configure(b *ant.ModelBuilder[Order]) {
ant.GenerateKey(b, &Orders.ID, ids.UUIDv7[uuid.UUID])
}
var Orders = ant.Fields[Order]()
order := &Order{Total: 5}
err := db.Orders.Insert(ctx, order)
// INSERT INTO "orders" ("id", "total") VALUES ($1, $2)
// -- $1 = 01a21f9d-64aa-7092-b2ba-5ea7ed9cdc62
ids.UUIDv7[T] returns a version 7 UUID as any type whose underlying type is [16]byte, so it fills a uuid.UUID of github.com/google/uuid, another library's UUID type, or a plain [16]byte. On PostgreSQL such a key is a uuid column, 16 bytes in the table and in each index, and so is every foreign key to it.
ids.UUID returns the same UUID as text, for a string key. A string key is a text column, whatever fills it: 37 bytes a key, and any string is accepted as one. To keep string fields and still have a uuid column, give the key a type:
type Memo struct {
ID string
Body string
}
func (Memo) Configure(b *ant.ModelBuilder[Memo]) {
ant.GenerateKey(b, &Memos.ID, ids.UUID)
b.Column(&Memos.ID).Type("uuid")
}
var Memos = ant.Fields[Memo]()
A foreign key to it takes the type too. Changing a key's type later rewrites every table that holds it, so choose before the tables fill.
UUID columns outside PostgreSQL
Migrations are PostgreSQL only, so on the other databases you write the column. A uuid.UUID is sent as its text, so the column must take that text:
| Database | Column | Refused, or wrong |
|---|---|---|
| MySQL | char(36) | binary(16) refuses the text: Data too long for column 'id' |
| MariaDB | uuid or char(36) | |
| SQLite | text | |
| SQL Server | char(36) | uniqueidentifier: see below |
SQL Server stores the text in a uniqueidentifier, but the driver reads one back in SQL Server's own byte order, so a uuid.UUID read from the row differs from the one written: 01a21faf-0845-78f0-... comes back as af1fa201-4508-f078-.... A Find with the key read back then returns ant.ErrNotFound, and saving a row loaded through a session returns ant.ErrConcurrency. Use char(36) there, or make the key the driver's own type, mssql.UniqueIdentifier from github.com/microsoft/go-mssqldb, filled by ids.UUIDv7[mssql.UniqueIdentifier], which reads a uniqueidentifier in its order.
ids.UUIDv7, ids.UUID and ids.ULID sort by creation time, so new rows land at the end of an index, where a random UUID such as uuid.New scatters them across it. For snowflake integers:
flakes, err := ids.NewSnowflake(1) // the node number
next := flakes.Next()
A UUID key on every model
GenerateKey goes in each model's Configure, since a builder is for one model. A base struct that every model embeds can't carry it, but it can carry a hook or a database default. Each way gives a model a key with no Configure of its own, and each covers different writes:
Insert, SaveChanges, Upsert | InsertMany | Databases | UUID version | |
|---|---|---|---|---|
GenerateKey in each model's Configure | Yes | Yes | All five | 7, from ids.UUIDv7 |
A BeforeInsert hook on the base | Yes | No, ant.ErrZeroKey: it runs no hooks | All five | 7 |
| A database default on the base | Yes | Writes the rows, but leaves the keys zero on the structs. SQLite refuses it | All but MySQL | What the default makes: 4 from PostgreSQL's gen_random_uuid(), 7 from its uuidv7() on 18 |
Outside PostgreSQL the column must take a UUID's text: see UUID columns outside PostgreSQL.
In each model
The most certain way, since every insert fills it. A model with no Configure and a uuid.UUID key is refused with ant.ErrZeroKey on its first insert, so a forgotten one shows up in the first test that writes a row.
type Customer struct {
ID uuid.UUID
Name string
}
func (Customer) Configure(b *ant.ModelBuilder[Customer]) {
ant.GenerateKey(b, &Customers.ID, ids.UUIDv7[uuid.UUID])
}
var Customers = ant.Fields[Customer]()
With a hook on the base
A hook method on an embedded struct is promoted to every model that embeds it, and the key check runs after BeforeInsert:
type Model struct {
ID uuid.UUID
CreatedAt time.Time
UpdatedAt time.Time
}
func (m *Model) BeforeInsert(ctx context.Context) error {
if m.ID == uuid.Nil {
m.ID = ids.UUIDv7[uuid.UUID]()
}
return nil
}
type Vendor struct {
Model
Name string
}
err := db.Vendors.Insert(ctx, &Vendor{Name: "Acme"})
// INSERT INTO "vendors" ("id", "created_at", "updated_at", "name") VALUES ($1, $2, $3, $4)
InsertMany runs no hooks, so it refuses these rows with ant.ErrZeroKey: set ID on each before the call. A model with a BeforeInsert of its own hides the base's, so it calls it:
func (v *Vendor) BeforeInsert(ctx context.Context) error {
if err := v.Model.BeforeInsert(ctx); err != nil {
return err
}
v.Name = strings.TrimSpace(v.Name)
return nil
}
With a database default
A default on the base's field makes the database fill the key, and ant reads it back with RETURNING:
type Record struct {
ID uuid.UUID `ant:"default=gen_random_uuid()"`
}
type Supplier struct {
Record
Name string
}
supplier := &Supplier{Name: "Acme"}
err := db.Suppliers.Insert(ctx, supplier)
// INSERT INTO "suppliers" ("name") VALUES ($1) RETURNING "id"
gen_random_uuid() gives a version 4 UUID, which is random, so new rows scatter across the index. PostgreSQL 18 has uuidv7(), which sorts by time. InsertMany writes DEFAULT for these keys but doesn't read them back, so its structs keep the zero uuid.UUID: read the rows again, or generate the keys in Go. SQLite takes no DEFAULT in a VALUES list, so InsertMany returns ant.ErrUnsupported there. MariaDB, SQLite and SQL Server read the key back as PostgreSQL does, with RETURNING or OUTPUT. MySQL has neither, so an insert there returns ant.ErrUnsupported: Supplier.Record.ID is a key the database fills, which mysql can only report through RETURNING.
Composite keys
CompositeKey spans several columns. FindKey takes the parts in the order declared. Tracking, Reload and Remove use the whole key.
type Grant struct {
UserID int64
Scope string
Level int
}
func (Grant) Configure(b *ant.ModelBuilder[Grant]) {
b.CompositeKey(ant.F(&Grants.UserID), ant.F(&Grants.Scope))
}
var Grants = ant.Fields[Grant]()
session := ant.Session(db)
grant, err := session.Grants.FindKey(ctx, int64(1), "write")
// SELECT ... FROM "grants"
// WHERE "grants"."user_id" = $1 AND "grants"."scope" = $2 LIMIT $3
grant.Level = 3
err = session.SaveChanges(ctx)
// UPDATE "grants" SET "level" = $1 WHERE "grants"."user_id" = $2 AND "grants"."scope" = $3
err = ant.Remove(ctx, session, grant)
err = session.SaveChanges(ctx)
// DELETE FROM "grants" WHERE "grants"."user_id" = $1 AND "grants"."scope" = $2
| Call | Error |
|---|---|
Find (it takes one key value) | ant.ErrNoKey |
FindKey with the wrong number of parts | ant.ErrKeyType |
FindKey with no such row | ant.ErrNotFound |
SaveChanges after changing part of a tracked key | ant.ErrKeyChanged |
To fetch many rows by composite key, use InTuples.
Times in a key
The tracker identifies a time.Time key by its UTC instant to the microsecond. A key in another zone finds the row already tracked, and a row read back is the instance you already have. Two keys less than a microsecond apart are one row to the tracker, even where SQL Server or SQLite could store them as two.
type Reading struct {
At time.Time
Value int
}
func (Reading) Configure(b *ant.ModelBuilder[Reading]) {
b.Key(&Readings.At).NotGenerated()
}
var Readings = ant.Fields[Reading]()
at := time.Date(2026, 1, 1, 12, 0, 0, 0, time.FixedZone("CET", 3600))
session := ant.Session(db)
err := session.Readings.Insert(ctx, &Reading{At: at, Value: 1})
same, err := session.Readings.Find(ctx, at.UTC()) // the tracked row, not a second copy
Sequences
A column can draw from a named sequence, which migrations create.
func (Invoice) Configure(b *ant.ModelBuilder[Invoice]) {
b.Column(&Invoices.Number).Sequence("invoice_numbers", ant.StartAt(1000), ant.IncrementBy(10))
}
Models without a key
A model with no ID field has no key. It inserts and queries like any other, and Find, DeleteByID and Reload return ant.ErrNoKey. b.NoKey() does the same for a model whose ID column isn't unique, such as an event log.
type LogLine struct {
ID int64
Text string
}
func (LogLine) Configure(b *ant.ModelBuilder[LogLine]) {
b.NoKey()
}
err := db.Logs.Insert(ctx, &LogLine{Text: "x"})
// INSERT INTO "log_lines" ("id", "text") VALUES ($1, $2) -- $1 = 0
db.Users.Find(ctx, "1") compiles and returns ant.ErrKeyType at runtime, because Find can't tie its key type to the model. An untyped number fits any integer key.
See it tested: tests/features/keys_and_identity