Field pointers as column names: compile-checked Go queries without codegen
Every time I've picked a database library for a Go project, the choice came down to which problem I'd rather live with. GORM and Bun take column names as strings, so Where("agee > ?", 18) compiles and fails when the query runs. ent and sqlc catch that at build time, but only after you've described your schema in their DSL or in SQL files and run a generator.
On a few projects I skipped both and just used stored procedures. (I'll touch on stored procedures later)
Go 1.27 added generic methods, and they make a third option practical: name columns with pointers to your own struct fields. In ant.Gt(&Users.Age, 18) the compiler checks that Age exists and that 18 is an int without needing any generated code. I built ant around that idea.
This post covers the technical approach on how a pointer turns back into a column, what the new generics allow us to do, what it costs, and what mistakes can't be caught by the compiler (yet)
The code is on GitHub.
The same query in four libraries
Users over 18 with their posts, sorted by name, ten at a time
- ant
- GORM 1.31
- Bun 1.3
- ent 0.14
var Users = ant.Fields[User]()
users, err := db.Users.
Include(&Users.Posts).
Where(ant.Gt(&Users.Age, 18)).
OrderBy(&Users.Name).
Limit(10).
All(ctx)
var users []User
err := db.WithContext(ctx).
Preload("Posts").
Where("age > ?", 18).
Order("name").
Limit(10).
Find(&users).
Error
var users []User
err := db.NewSelect().
Model(&users).
Relation("Posts").
Where("age > ?", 18).
Order("name").
Limit(10).
Scan(ctx)
users, err := client.User.Query().
WithPosts().
Where(user.AgeGT(18)).
Order(user.ByName()).
Limit(10).
All(ctx)
tools/compare runs all four against the same PostgreSQL database and checks that they return the same rows. Breaking them intentionally show the tradeoffs of each approach:
| Mistake | ant | GORM | Bun | ent | sqlc |
|---|---|---|---|---|---|
Misspelled column, agee | compile error | runtime | runtime | compile error | sqlc generate |
"18" for an int | compile error | runtime | runtime | compile error | compile error |
Misspelled relation, Psots | compile error | runtime | runtime | compile error | sqlc generate |
| Column of another model | antvet | runtime | runtime | compile error | sqlc generate |
| No generate step | yes | yes | yes | no | no |
ent and sqlc catch as much as ant does, and in ent's case even more. GORM is also dipping it's toes in generics, it has a generics API and an optional CLI that generates typed field helpers. It uses code gen, and it's opt-in, but realistically if you already run GORM it's the cheapest way to get some of these checks. If you'd rather move, Migrating from GORM maps each GORM call to ant and covers moving one model at a time.
What the compiler says
These are from go build on Go 1.27.3.
A misspelled field:
db.Users.Where(ant.Gt(&Users.Agee, 18))
Users.Agee undefined (type *User has no field or method Agee)
A string where the column is an int:
db.Users.Where(ant.Gt(&Users.Age, "18"))
cannot use "18" (untyped string constant) as int value in argument to ant.Gt
A misspelled relation:
db.Users.Include(&Users.Psots)
Users.Psots undefined (type *User has no field or method Psots)
A relation used as a value. Eq wants a comparable value, a slice isn't one:
db.Users.Where(ant.Eq(&Users.Posts, nil))
[]Post does not satisfy comparable
They're errors you would get for any struct field. gopls sees them while you type, and renaming Age with gopls renames it in every query automatically.
Basically ant leverages the compiler and gopls to catch mistakes early!
How &Users.Age becomes a column
ant.Fields[User]() returns a "probe", that is just an empty *User that exists only so that its fields have addresses. &Users.Age is a pointer to that probe's Age offset... So how is this helpful..?
The first call to Fields[User]() reflects over User, caches its columns, relations and field offsets, allocates a single User and stores its address in a package level list. (future calls return the same pointer)
So, to resolve a field pointer, ant checks the list for the probe whose memory range contains the address, subtracts the base to get an offset, then looks up the field with that offset and the pointer's static type.
The type is needed in the lookup because a struct and its first field share an address. &Users.Base and &Users.Base.ID point at the same byte. Resolve is generic over V, so reflect.TypeFor[V]() tells them apart without any extra work at the call site.
Here is a snippet; the full version is in internal/meta/meta.go:
func Probe[T any]() *T {
model := Of[T]() // reflected once per type, then cached
// (under mu: return the existing probe for model, if there is one)
p := new(T)
probes = append(probes, probe{unsafe.Pointer(p), uintptr(unsafe.Pointer(p)), model})
return p
}
func Resolve[V any](ptr *V) (Ref, bool) {
addr := uintptr(unsafe.Pointer(ptr))
t := reflect.TypeFor[V]()
mu.RLock()
defer mu.RUnlock()
for _, p := range probes {
if addr < p.base || addr >= p.base+p.model.Type.Size() {
continue
}
off := addr - p.base
for _, f := range p.model.Fields {
if f.Offset == off && f.Type == t {
return Ref{Model: p.model, Field: f}, true
}
}
// relations are matched the same way
}
return Ref{}, false
}
A lookup takes about 21 ns without allocations. Measured in tests/benchmarks over five runs on a Ryzen 5 3600, with a few probes registered.
The scan is linear, so an application with hundreds of models pays more per lookup, though still far less than a database round trip. I can smell an optimization here... please give suggestions...
The catch is that the probe's address has to stay fixed for the life of the process. Go's garbage collector doesn't move objects today, but there hasn't been a promise that it never will.
Bjorn (huge thanks ❤️) on Gophers Slack pushed on exactly this point. Turns out, runtime.Pinner can pin each probe when it's created, which keeps it in place even under a future moving collector, and also tells today's collector about the pointer arithmetic on it. ant now does exactly that: every probe is pinned when it's allocated, and lookups are as fast as before.
Why this needed Go 1.27
ant.Gt is an ordinary generic function func Gt[V Ordered](field *V, value V) Cond and it would have compiled on Go 1.18. What needed 1.27 is the chaining around it.
OrderBy has to know the field's type so that it can require an orderable one, and Include needs the relation's element type so its optional shaping function gets a typed *Query[Post]. Both need type parameters of their own, and until 1.27 a method couldn't declare any.
If you try to, the compiler will complain:
generic method requires go1.27 or later
Without generic methods, the API has to be package level functions, and those nest inside out:
// before 1.27: the reader starts in the middle
users, err := ant.OrderBy(
ant.Include(
db.Users.Where(ant.Gt(&Users.Age, 18)),
&Users.Posts,
),
&Users.Name,
).Limit(10).All(ctx)
// 1.27: top to bottom
users, err := db.Users.
Include(&Users.Posts).
Where(ant.Gt(&Users.Age, 18)).
OrderBy(&Users.Name).
Limit(10).
All(ctx)
The older approach works, but you read it from the middle outwards in the reverse order to the SQL that it builds, so adding a step means rewrapping the whole expression. As a cherry on top, typing db.Users. in an editor wouldn't offer any operations, because they aren't methods. Another approach was methods that take any, which basically defeats the whole point.
The methods that need their own type parameters are Join and its variants, OrderBy, Include, IncludeOne, Find, With, Column, Omit, GroupBy, Load, Tx on the context, and most of the model builder.
Joins were an absolute nightmare, they'll get a separate post.
Writing back: change tracking
For writes, ant doesn't ask which fields you changed, it compares each entity with what it loaded.
A noptable issue I was aware of and wanted to avoid was GORM's Updates, where a struct skips zero-valued fields, which is documented:
db.Model(&user).Updates(User{
Name: "Ada",
Age: 0,
Active: false,
})
UPDATE "users" SET "updated_at"='…',"name"='Ada' WHERE "id" = 1
-- no age, no active
Using Select("Age", "Active") or a map does write them, but you have to remember to use them.
In ant you change the loaded entity and call SaveChanges:
session := ant.Session(db)
user, err := session.Users.Find(ctx, id)
user.Age = 0
user.Active = false
err = session.SaveChanges(ctx)
UPDATE "users" SET "age" = $1, "active" = $2, "updated_at" = $3
WHERE "users"."id" = $4
ant keeps a snapshot of every entity it loads and diffs against it on save, so 0, false, "" and nil count as changes like any other value, and only the changed columns are written.
And as a consequence of this approach, passing the model around between functions to make changes is simple and intuitive.
Also, this approach narrows the window for potential race conditions, since changes are only applied to altered fields. In GORM, for example, 2 saves will overwrite each other's changes even if they modify different fields.
What it costs
From tools/compare, time per operation in microseconds, median of 10 runs:
| ant | ant NoTracking | GORM | Bun | ent | Plain SQL (baseline) | ||
|---|---|---|---|---|---|---|---|
| Read 1000 rows | 2,799 | 1,688 | 3,285 | 2,259 | 2,226 | 1,557 | |
| Find one by key | 406 | 389 | 416 | 372 | 383 | 365 | |
| Load, edit, save | 830 | – | 861 | 779 | 1,784 | 806 |
Ran on my Ryzen 5 3600 with Go 1.27.3 and PostgreSQL 17.11 in Docker on WSL2, with synchronous_commit=off; see more at benchmarks page. My machine wasn't idle during these runs, so treat it with a grain of salt. I'll rerun them in a more controlled environment some day.
With tracking on, reading 1000 rows takes 1.7 times as long as with NoTracking and uses three times the memory (823 KiB against 277 KiB). With tracking off, ant is 8% slower than plain database/sql on that read.
Single-row work lands within a few percent of everything else. So essentially, accounting for round-trip time, these single row results might as well be printed out and used as toilet paper.
Allocations are where ant is weakest: 118 to find one row, against 41 for Bun and 36 for plain SQL, and only ent allocates more on some small queries. That needs work..
The ent figure on edit: its UpdateOne re-reads the row inside a transaction, so that benchmark sends four statements where the others send two.
Where it falls short
Some mistakes still compile... For example, a field pointer carries its field and type, but a condition isn't tied to a model, so these build fine and fail at the terminal call (All, First, Find and so on), not at Where. Here are some more that I know of:
&u.Ageon a localUserinstead of the probe givesErrNotProbe.- A relation where a column belongs, like
Column(&Users.Posts), givesErrNotColumn. - A plain slice column where a relation belongs, like
Include(&Users.Tags)on a[]stringfield, givesErrNotRelation. - A field of a model the query doesn't use, like
db.Users.Where(ant.Eq(&Posts.Title, "x")), givesErrWrongModel. Find(ctx, "42")on a model with anint64key givesErrKeyTypebecauseFindis generic over the key and the compiler can't know which key type a model has.
antvet, a go vet analyzer in the repo, catches a few of these cases. (wip ❤️)
condition on Post in a query of User
ant.Gt needs a field of a probe from ant.Fields, not of an ordinary variable
Find key is string, and User has a key of type int64
It's a separate step you have to add to CI, and ent and sqlc don't have any of these runtime-only cases in the first place.
The rest is the usual for a young project. ant needs Go 1.27 or later, since generic methods are the reason the API looks the way it does, and there's no fallback for older toolchains.
It's pre-1.0, so the API can still change, though docs/api.txt records every exported name so that changes are deliberate. Queries and writes work on PostgreSQL, MySQL, MariaDB, SQLite and SQL Server, but the migrations and EnsureCreated are PostgreSQL only; on the other databases you keep running plain SQL migrations with whatever tool you use now. There are no down migrations: to undo a change, you write a new one. (Down migrations are inherently unsafe and I don't wan't the headache)
Regarding stored procedures
I believe that using only an ORM or only pure sql is not ideal either way. You lose something either way. However, using both.... That's an attractive idea, at least to me.
You get the benefits of an ORM for simpler logic, and the ability to delegate complex queries or performance critical operations to stored procedures. ant's migrations have a folder for repeatable migrations, that's an ideal place for your stored procedures
CREATE FUNCTION quote_order(req jsonb) RETURNS jsonb
LANGUAGE plpgsql AS $$
BEGIN
RETURN jsonb_build_object(
'total', (req->>'qty')::int * (req->>'price')::numeric,
'status', 'ok'
);
END $$;
type QuoteRequest struct {
Qty int `json:"qty"`
Price float64 `json:"price"`
}
type QuoteResult struct {
Total float64 `json:"total"`
Status string `json:"status"`
}
res, err := ant.Raw[ant.JSON[QuoteResult]](
db,
"SELECT quote_order(@req)",
sql.Named("req", ant.JSON[QuoteRequest]{V: req}),
).First(ctx)
// res.V is a QuoteResult
This is the setup I’ve always wanted, and the flexibility is why I never managed to move to an existing ORM
Try ant
The Quick start runs a complete program on SQLite with no server.
Why ant has the longer comparison with GORM, Bun, ent, sqlc, xorm and pop. The code is on GitHub, and ant-examples has complete programs.
What I'd like to hear
Mostly, whether &Users.Age reads naturally in real code. The probe is a package-level variable with the same name as the table field on your context (db.Users), which I expect some people to like and others to find confusing.
I'd also like to know whether you'd add antvet to CI or a pre-commit hook, or whether a check outside the compiler defeats the purpose for you. And if you've tried to move a codebase off GORM or Bun, what stopped you?
A lot of ant's code was written with AI assistance based off of a proof of concept implementation made initially. The feature tests in tests/features, the cross-library checks in tools/compare and the decision log in docs/DECISIONS.md are how I check it.
