/ant:antfrom ant
Writes, reviews and debugs Go code using the ant ORM, a typed ORM with column pointers instead of strings. Use when Go files import github.com/skudra-go/ant or mention ant models, tables, migrations, or anttest.
Ships in ant. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
ant is a Go ORM. Models are plain structs, columns are pointers to the fields of a probe value, and there is no code generation. It needs Go 1.27 or later, for generic methods.
Your training data probably has little or no ant in it. Do not guess from GORM, Bun,
ent or sqlx. Calls such as db.Where("age > ?", 18), Preload("Posts"),
AutoMigrate, db.Model(&u).Updates(...) or First(&u) do not exist. When you are
unsure of a name, check before you write it:
go doc github.com/skudra-go/ant <Name>, or go doc github.com/skudra-go/ant.Query
for a type's methods. This matches the version in the user's go.mod.tests/features/<section>/, are small,
runnable examples of every feature.type User struct {
ant.Base // ID int64, CreatedAt, UpdatedAt; optional
Name string
Email string `ant:"unique"`
Age int
Bio *string // nullable
Posts []Post // a relation: one-to-many through Post.UserID
}
type Post struct {
ant.Base
UserID int64
Title string
Published bool
User *User // a relation: many-to-one through Post.UserID
}
// The database: embeds ant.Context and holds one ant.Table per model. Tables
// can also sit in an embedded or named struct field that groups a domain's
// tables; a Table field must be exported.
type AppDB struct {
ant.Context
Users ant.Table[User]
Posts ant.Table[Post]
}
// Probes: one per model, at package level. &Users.Age names the users.age column.
var (
Users = ant.Fields[User]()
Posts = ant.Fields[Post]()
)
db, err := ant.Open[AppDB](ctx, postgres.Dialect, dsn)
if err != nil {
return err
}
defer db.Close()
adults, err := db.Users.
Where(ant.Gt(&Users.Age, 18)).
Include(&Users.Posts).
OrderBy(&Users.Name).
Limit(10).
All(ctx)
ant.Open fills in every ant.Table field and fails at startup if a model can't
be mapped: an unknown tag key, two fields on one column, a relation with no
foreign key, or []*Post where []Post is meant. It reports every broken model
at once, and each error says what to write instead: GORM's primaryKey,
size:100 and column:name are refused with ant's equivalent. Open once per
process, as ant.Open[AppDB], never ant.Open[*AppDB]. Never construct AppDB
yourself._ "github.com/jackc/pgx/v5/stdlib" for
PostgreSQL, _ "modernc.org/sqlite", _ "github.com/go-sql-driver/mysql" or
_ "github.com/microsoft/go-mssqldb".postgres.Dialect, mysql.Dialect, mysql.MariaDB, sqlite.Dialect,
sqlserver.Dialect, from github.com/skudra-go/ant/dialect/<name>.parseTime=true,
and ant.Open refuses a DSN without it. SQLite wants
_pragma=foreign_keys(1)&_pragma=busy_timeout(5000)&_txlock=immediate,
and ant.Open refuses a DSN that does not set all three. The driver's
_busy_timeout / _timeout shorthand is also accepted; empty values are not
choices. foreign_keys(0), busy_timeout(0), and _txlock=deferred are
explicit opt-outs.Every place that names a column takes &Probe.Field, never a string. The compiler
checks the field name and that the value has the field's type:
db.Users.Where(ant.Eq(&Users.Name, "Ada")) // fine
db.Users.Where(ant.Gt(&Users.Age, 18)) // fine: 18 is an int, like Age
db.Users.Where(ant.Eq(&Users.Bio, nil)) // IS NULL
db.Posts.Where(ant.Eq(&Posts.Published, true)) // each model has its own probe
Mistakes the compiler can't see, which return an error when the query runs:
db.Posts.Where(ant.Gt(&Users.Age, 18))
gives ant.ErrWrongModel. In a join, conditions on either model are fine.&age or &user.Age, gives
ant.ErrNotProbe. Probes are only for naming columns; they never hold data.db.Users.Find(ctx, "1") gives ant.ErrKeyType.Calls that take columns of mixed types take ant.FieldRef, made with
ant.F(&Users.Name).
OrderItem is
order_items. Columns are snake case: UserID is user_id.ID is the primary key. A zero integer key means "generate one",
and the database's key is copied back after an insert. A key of another type,
such as uuid.UUID or string, is yours to fill: set it, generate it in
Configure with ant.GenerateKey(b, &Docs.ID, uuid.New), or give it a default
(ant:"default=gen_random_uuid()"). Inserting one at its zero value returns
ant.ErrZeroKey. For keys that sort by time, generate with
ids.UUIDv7[uuid.UUID] (package ant/ids): a uuid.UUID key is a uuid
column, while a string key, such as one ids.UUID fills, is a text column.time.Time fields named CreatedAt and UpdatedAt are maintained by ant, on any
model. ant.Base is just ID, CreatedAt and UpdatedAt. A zero UpdatedAt,
as in a struct decoded from a request body, is stamped on every save.sql.Null[T] field. A plain field can't read
NULL. Zero values are always written, never skipped.ant:"-" (not a column), column=name, unique, default=expr (a zero
value means "use the database default" on insert, so Active bool with
default=true never inserts false: make it *bool with .NotNull() where the
zero must be stored; updates, including an upsert's, write the zero; field rules
skip the zero on Insert and SaveChanges inserts, but still check updates and
upserts), readonly (filled by the database:
a generated column or one a trigger keeps, read back after every insert and
update), writeonly, immutable,
computed (filled by Query.With), version (optimistic concurrency, a signed
integer field),
embedded / embedded,prefix=x_. Combine with commas. Keys that contradict
each other, such as readonly,writeonly or version,immutable, and two
version or ant.DeletedAt fields in one model, fail at Open with
ant.ErrBadSchema.ant.DeletedAt turns on soft deletes. In JSON it is null for
a live row and the deletion time otherwise, as a *time.Time is. ant.JSON[T]
stores a value as JSON. A number read into an interface (map[string]any)
is a json.Number, not a float64.ant.Base is id, createdAt,
updatedAt, ant.Page is items, total, number, size, and
ant.CursorPage is items, next, so a handler can return them as they are.time.Duration is
interval, net.IP and netip.Addr are inet, netip.Prefix is cidr,
json.RawMessage and map[string]any are jsonb, decimal.Decimal is numeric, uint64 is
numeric(20,0) (a key the database generates stays bigint), and a plain slice
is an array, as []string is text[]. A type with no column type fails with
ant.ErrNoColumnType until b.Column(&...).Type("...") names one.Open refuses such a field with ant.ErrNoColumnType, naming it:
wrap it as ant.JSON[T], or give the type a driver.Valuer and sql.Scanner.Users ant.Table[User]; Open refuses a
*ant.Table[User] field.Configure method on the model:func (Post) Configure(b *ant.ModelBuilder[Post]) {
b.Table("articles")
b.Index(&Posts.Title)
b.BelongsTo(&Posts.User).OnDelete(ant.Cascade)
}
Relations are found by name: []Post on User with UserID on Post is
one-to-many, *User on Post is many-to-one. Relation slices hold values ([]Post),
not pointers. When the names don't fit, declare it with b.HasMany, b.HasOne,
b.BelongsTo or b.ManyToMany and .ForeignKey(&Posts.AuthorID). Two relations to
the same model (Posts []Article and Edited []Article) are ErrNoForeignKey until
one sets .ForeignKey, because both would be guessed onto one key. A relation is not
a column, so it can't go in Where or OrderBy.
A query is built from a table (db.Users) and runs at the call that takes ctx.
Builder methods never return errors; the terminal call returns everything collected.
| Call | Returns |
|---|---|
All(ctx) | []*T; no rows is an empty slice, not an error |
First(ctx) | *T or ant.ErrNotFound; order the query first |
Single(ctx) | *T, ant.ErrNotFound or ant.ErrMultipleRows |
Find(ctx, key) | *T by primary key, or ant.ErrNotFound |
Count(ctx), Exists(ctx) | int64, bool |
Each(ctx) | an iter.Seq2[T, error] that streams; no Include, not tracked; in a transaction, no other statement inside the loop (ant.ErrQueryInEach) |
Page(ctx, page, size), After(ctx, cursor, size) | numbered pages, cursor pages; After over a column that can be NULL needs .NullsFirst() or .NullsLast() |
Chunk(ctx, size, fn) | batches; ChunkByKey if fn changes the rows; a session stops tracking each batch once fn leaves nothing to save, so save inside fn |
ant.Pluck(ctx, query, &Users.Name) | one column as []string |
Conditions: ant.Eq, Ne, Gt, Gte, Lt, Lte, Between, In, NotIn,
Like, ILike, IsNull, IsNotNull, EqCol (column to column), And, Or, Not,
InTuples, AnyOf. Several conditions in one Where, or several Where calls, are
joined with AND. ant.In(&Users.Age) with no values matches nothing.
NULL reads as Go: ant.Eq(&Users.Bio, nil) is IS NULL, and on a nullable column
ant.Ne(&Users.Bio, &x), NotIn and ant.Not(ant.Eq(...)) with a value also match
the NULL rows (bio <> $1 OR bio IS NULL). Ordering comparisons stay SQL's:
Gt, Lt and ant.Not(ant.Gt(...)) never match NULL.
Every helper takes a field of any type, and the database checks that it can
order, compare or add it up: OrderBy, ThenBy, Latest, Gt to Between,
Like, ILike, Lower, Past, Future, Today, DatePart, Sum, Avg, Min,
Max, SumOf, MaxOf, SumRelated and Inc work on a *time.Time, *string,
*int, sql.Null[T], uuid.UUID, decimal.Decimal or ant.DeletedAt field as
on a plain one. Model money as decimal.Decimal. A comparison with a nil pointer
matches nothing, as in SQL: only Eq, Ne and In turn nil into IS NULL.
ant.Inc(&Posts.Votes, 1) on a Votes *int counts a NULL from 0, and
SumOf over no rows returns the zero value (nil for a pointer field).
On PostgreSQL, postgres.Match(&Posts.Title, "english", query) converts a text
column with to_tsvector, writing the configuration into the SQL, so an index on
to_tsvector('english', title) serves it. For a stored tsvector column, use
postgres.MatchVector(&Posts.SearchVector, "english", query), which applies the
full-text operator directly and can use the vector's index.
users, err := db.Users.
Where(
ant.Or(
ant.Lt(&Users.Age, 18),
ant.Like(&Users.Name, "A%"),
),
ant.Not(ant.Eq(&Users.Name, "Bob")),
).
OrderBy(&Users.Age).
ThenByDesc(&Users.Name).
All(ctx)
To sort by a column a request names, list the names it may use in a
map[string]ant.FieldRef and order by the entry's Asc() or Desc(). Refuse a
name that isn't in the map: its zero FieldRef makes the query fail with
ant.ErrNotProbe.
sorts := map[string]ant.FieldRef{
"name": ant.F(&Users.Name),
"age": ant.F(&Users.Age),
}
users, err := db.Users.Order(sorts["age"].Desc(), sorts["name"].Asc()).All(ctx)
Relations load only when asked. An unloaded relation is nil; a loaded one with no
rows is an empty slice. There is no lazy loading. Include (for []T) and
IncludeOne (for *T) add one query per relation, however many parents:
users, err := db.Users.
Include(&Users.Posts, func(q *ant.Query[Post]) *ant.Query[Post] {
return q.Where(ant.Eq(&Posts.Published, true)).OrderByDesc(&Posts.CreatedAt)
}).
All(ctx)
posts, err := db.Posts.IncludeOne(&Posts.User).All(ctx)
Filter by a relation without loading it with ant.Has(&Users.Posts, conds...),
ant.HasNone and ant.HasOne. Joins return pairs through Select; results in your
own struct come from ant.Project:
titles, err := db.Posts.
Join(&Posts.User).
Where(ant.Eq(&Users.Name, "Alice")).
Select(func(p *Post, u *User) string { return u.Name + ": " + p.Title }).
All(ctx)
A join and a projection have Count, Exists, ToSQL and Debug, as a query
does, so a page of joined rows can show its total.
In ant.Project, a NULL from a left join's side or an aggregate over no rows
reads into a plain field as its zero value, as MaxOf returns one. Wrap the
expression in ant.Nullable and use an sql.Null[V] field to tell "no row"
from a stored zero: ant.IntoExpr(&R.Newest, ant.Nullable(ant.Max(&Posts.ID))).
Raw SQL scans into models, any struct or a single value. Use ? placeholders on
every database, and pass values as arguments, never in the text:
rows, err := ant.Raw[User](db, `SELECT * FROM users WHERE age > ?`, 18).All(ctx) // []User
countPtr, err := ant.Raw[int](db, `SELECT count(*) FROM users`).First(ctx) // *int
alice := &User{Name: "Alice", Email: "[email protected]"}
err := db.Users.Insert(ctx, alice) // fills alice.ID, CreatedAt, UpdatedAt
// Bulk update: explicit assignments, so zeros and nil are written.
n, err := db.Users.
Where(ant.Eq(&Users.ID, alice.ID)).
Update(ctx, ant.Set(&Users.Bio, nil), ant.Inc(&Users.Age, 1))
n, err = db.Users.Where(ant.Lt(&Users.Age, 18)).Delete(ctx)
err = db.Users.DeleteByID(ctx, alice.ID)
// Insert, or update on a unique conflict.
wrote, err := db.Users.Upsert(ctx, alice, ant.OnConflict(&Users.Email))
Update and Delete hang off a query, not the table: db.Users.Where(...).Update.
With no condition they return ant.ErrNoCondition; db.Users.Unfiltered() opts out
on purpose. One assignment per field: Set and Inc on the same field is an error.Insert also inserts the new entities a struct points at, parents first, and fills
in foreign keys. InsertOnly leaves relations alone. InsertMany is for
thousands of rows.CreatedAt, Version,
DeletedAt, and its relations, which Insert inserts too. InsertOnly drops
the relations, not the rest. Decoded into a tracked entity loaded with its posts,
"Posts": [] deletes them at SaveChanges.Update and Delete run no hooks and don't change tracked structs.FirstOrCreate(ctx, entity, conds...) reads or inserts, safely under races when
the condition is on a unique column. In a transaction, a row another writer
inserted first is read FOR UPDATE, so changing it next cannot deadlock.ant.IsUniqueViolation(err),
ant.IsForeignKeyViolation(err), ant.IsRetryable(err).The context from ant.Open does not track: share it between requests, and read
and write through it directly. A session, ant.Session(db), tracks: entities its
All, First, Single, Find, Include and Insert return are tracked.
Change the struct and call SaveChanges, which writes only the changed columns,
in one transaction:
session := ant.Session(db) // one per request, job or goroutine
user, err := session.Users.Find(ctx, id)
if err != nil {
return err
}
user.Age++
err = session.SaveChanges(ctx)
// UPDATE "users" SET "age" = $1, "updated_at" = $2 WHERE "users"."id" = $3
ant.ErrConcurrentUse. Call ant.Session(db) per request.SaveChanges saves only what its own
context tracks: an entity loaded through db, the root, or through another
session is not saved, and SaveChanges still returns nil. Load it through the
session, or ant.Attach it first. HasChanges(ctx) reports whether there is
anything to save. antvet reports the slip.SaveChanges, ant.Add,
ant.Attach, ant.MarkModified, ant.Remove and ant.TrackGraph return
ant.ErrNoTracking. ant.WithTracking(true) on Open makes the root track,
for a script that does one thing at a time.Open. A session needs no closing; closing it closes the
shared pool.ant.Add(ctx, session, entity) queues an insert and ant.Remove(ctx, session, entity) a
delete, for the next SaveChanges.user.Posts and calling SaveChanges deletes that post (or clears its foreign key
if the key is nullable). Appending inserts. A relation that was never loaded (nil)
is left alone. A loaded has-one pointer works the same way: replacing or clearing
user.Profile deletes the old profile (or clears its key), unless another parent
holds it now. A has-one with Latest or Oldest is a view of many rows, so
replacing or clearing it deletes nothing. A soft-deleted old row keeps its key,
so a unique index on that key must leave deleted rows out
(WHERE deleted_at IS NULL). A target-side Eq in a relation Where assigns its
value when the relation gains a row; other scope conditions only filter reads.
An unmoved loaded relation does not reapply the scope over explicit edits.NoTracking() on a query skips tracking for read-only work and is faster. Each,
Column, Omit, Raw, Select and Project results are never tracked, so
changing them saves nothing. With rows are tracked; their computed fields are
never compared or written.db.Users.Reload(ctx, e) rereads it. A locking
read (ForUpdate, ForShare) puts the row into that instance, or returns
ErrConcurrency if the instance has unsaved changes and the row has moved.user.Posts[0].User is user, and json.Marshal
fails with "encountered a cycle". A context that does not track returns a tree.
To encode, read with NoTracking(), map to a DTO, or tag the back reference
json:"-".SaveChanges returns ant.ErrConcurrency when the row was deleted, or its
version changed, since it was loaded. A version set on a loaded entity, such
as the one a client sent back, is the one checked.BeforeInsert(ctx context.Context) error,
AfterLoad, BeforeUpdate, BeforeDelete and the rest. A query made in a hook
must use the hook's ctx, or it fails with ErrConcurrentUse. That ctx is
bound to the write's transaction, so a query or write through any context on
the pool, even a global db, runs in it and rolls back with it. For a write
that must stay, use ant.InTx(ctx, db) with db in no transaction. A Tx in
a hook is a savepoint: no Isolation, and Attempts does not retry.err := db.Tx(ctx, func(tx *AppDB) error {
bob := &User{Name: "Bob", Email: "[email protected]"}
if err := tx.Users.Insert(ctx, bob); err != nil {
return err
}
return tx.Posts.Insert(ctx, &Post{UserID: bob.ID, Title: "First"})
})
tx, not db; work on db runs outside the transaction.
tx is your own *AppDB type. Code that holds db, such as a repository built
at startup, or a session, runs in the transaction when given
ctx := ant.InTx(ctx, tx): its writes, and its SaveChanges and Tx as a
savepoint. Once the transaction ends, a kept bound ctx runs nothing.nil and rolls back on an error or panic. A Tx inside a Tx is a
savepoint. SaveChanges inside one uses a savepoint, and a rollback undoes the
tracker's view of the save too: it forgets what the transaction began tracking,
and an entity loaded before it keeps its changes, pending. Load inside the
transaction what it changes.ant.Isolation(sql.LevelSerializable),
ant.ReadOnly(), ant.Attempts(3) to rerun after a deadlock or serialization
failure.ForUpdate() on a query locks the rows it reads. SQL Server returns
ant.ErrUnsupported, and so does SQLite, except in a writable transaction on a
DSN with _txlock=immediate, which already holds the write lock. Count,
Exists and the aggregates of a locked query run without the lock.Match with errors.Is and errors.As, never by text. The common ones:
ErrNotFound, ErrMultipleRows, ErrNoCondition, ErrConcurrency,
ErrConcurrentUse, ErrUnsupported (the database can't do it; ant refuses before
sending SQL), ErrNotProbe, ErrWrongModel, ErrKeyType, ErrNoForeignKey,
ErrPaging (a page number or size below 1, or a negative Limit or Offset: a
client's mistake when it comes from a request), ErrCursor, and ErrQueryInEach.
ant.FailedSQL(err) returns the statement behind an error, without values. A table
that does not exist gives ant.SQLState(err) == "42P01" on every database.
PostgreSQL has everything. MySQL, MariaDB, SQLite and SQL Server have queries,
writes, relations, tracking and transactions, but no migrations and no
EnsureCreated: create their tables with your own SQL or tool. Some features vary:
SQL Server has no upsert (use ant.Merge), MERGE needs PostgreSQL 15 or SQL Server,
UpdateReturning is not on MySQL or MariaDB. When unsure, fetch
https://skudra.net/reference/databases.md.
Structs are the source of truth. diff writes a plain SQL file from what changed;
up applies it. There are no down migrations: undo with a new migration. The tool is
a small program in the user's module:
package main
import (
_ "github.com/jackc/pgx/v5/stdlib"
"github.com/skudra-go/ant/dialect/postgres"
"github.com/skudra-go/ant/migrate"
"example.com/app/models"
)
func main() {
migrate.Main[models.AppDB](postgres.Dialect)
}
If the application opens with ant.WithNaming or ant.WithConvention, pass the same options in migrate.Config{Options: ...}, or the migrations use the default names.
go run ./cmd/migrate diff add_bio # writes migrations/versions/0002_add_bio.up.sql
go run ./cmd/migrate up # needs DATABASE_URL or --dsn
go run ./cmd/migrate check # in CI: fails if a struct changed without a migration
After changing a model, run diff and show the user the SQL; don't hand-write the
migration it would generate. db.EnsureCreated(ctx) creates tables straight from the
structs, for experiments and tests only.
Test against a real database; ant has no fake. anttest.Isolate gives each test a
context in a transaction that rolls back when the test ends:
var shared *AppDB // opened once, in TestMain
func TestSignup(t *testing.T) {
db := anttest.Isolate(t, shared)
err := db.Users.Insert(t.Context(), &User{Name: "Ann", Email: "[email protected]"})
if err != nil {
t.Fatal(err)
}
}
anttest.NewFactory builds valid entities, and q.ToSQL() returns a query's SQL
without a database.
&Probe.Field from that model's probe, declared with
ant.Fields[T]().ctx, and its error is checked.ant.Session.db.Tx uses tx.go doc or the docs.go vet -vettool=$(which antvet) ./.... It
catches wrong-model and non-probe pointers, wrong key types, and changes saved
through a context that did not load them. Install it with
go install github.com/skudra-go/ant/tools/antvet/cmd/antvet@latest.What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub skudra-go/ant --plugin antOther plugins' skills for the same job