Quick start
A small program that saves a user with two posts, loads them back and updates one column. You need Go 1.27 or later.
SQLite needs nothing but Go. PostgreSQL needs Docker, and it's the one to build a real project on, because migrations only support PostgreSQL so far. The two versions differ only in how they connect and create tables.
Set up
- SQLite
- PostgreSQL
mkdir hello && cd hello
go mod init example.com/hello
go get github.com/skudra-go/ant modernc.org/sqlite
modernc.org/sqlite is pure Go, so no C compiler is needed.
Or clone the same program from examples/hello:
git clone https://github.com/skudra-go/ant-examples
cd ant-examples/examples/hello
go run .
mkdir hello && cd hello
go mod init example.com/hello
go get github.com/skudra-go/ant github.com/jackc/pgx/v5/stdlib
docker run -d --name hello-db -p 127.0.0.1:5432:5432 \
-e POSTGRES_PASSWORD=hello postgres:17
The program
- SQLite
- PostgreSQL
package main
import (
"context"
"fmt"
"log"
_ "modernc.org/sqlite" // the "sqlite" driver, in pure Go
"github.com/skudra-go/ant"
"github.com/skudra-go/ant/dialect/sqlite"
)
type User struct {
ant.Base // ID, CreatedAt, UpdatedAt
Name string
Email string `ant:"unique"`
Age int
Posts []Post // found through Post.UserID
}
type Post struct {
ant.Base
UserID int64
Title string
}
type AppDB struct {
ant.Context
Users ant.Table[User]
Posts ant.Table[Post]
}
var Users = ant.Fields[User]()
// Migrations run on PostgreSQL only for now, so on SQLite the tables are plain SQL.
const tables = `
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
created_at TIMESTAMP NOT NULL,
updated_at TIMESTAMP NOT NULL,
name TEXT NOT NULL,
email TEXT NOT NULL UNIQUE,
age INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS posts (
id INTEGER PRIMARY KEY,
created_at TIMESTAMP NOT NULL,
updated_at TIMESTAMP NOT NULL,
user_id INTEGER NOT NULL REFERENCES users (id),
title TEXT NOT NULL
)`
func main() {
ctx := context.Background()
// foreign_keys turns on the REFERENCES checks, which SQLite skips by default.
// busy_timeout and _txlock=immediate make concurrent writers wait their turn
// instead of failing with "database is locked".
const dsn = "file:hello.db?_pragma=foreign_keys(1)&_pragma=busy_timeout(5000)&_txlock=immediate"
db, err := ant.Open[AppDB](ctx, sqlite.Dialect, dsn)
if err != nil {
log.Fatal(err)
}
defer db.Close()
if _, err := ant.Raw[any](db, tables).Exec(ctx); err != nil {
log.Fatal(err)
}
// Insert Alice and her posts on the first run, and find her on later ones.
alice, created, err := db.Users.FirstOrCreate(
ctx,
&User{
Name: "Alice",
Email: "alice@example.com",
Age: 30,
Posts: []Post{{Title: "Hello"}, {Title: "Second post"}},
},
ant.Eq(&Users.Email, "alice@example.com"),
)
if err != nil {
log.Fatal(err)
}
if created {
fmt.Println("Created", alice.Name)
}
// Load every adult with their posts. ant.Gte(&Users.Age, "18") wouldn't compile.
adults, err := db.Users.
Where(ant.Gte(&Users.Age, 18)).
Include(&Users.Posts). // one query for every user's posts
OrderBy(&Users.Name).
All(ctx)
if err != nil {
log.Fatal(err)
}
for _, u := range adults {
fmt.Printf("%s is %d and has %d posts\n", u.Name, u.Age, len(u.Posts))
}
// Change a loaded user and save. Only the age column is written.
adults[0].Age++
err = db.SaveChanges(ctx)
if err != nil {
log.Fatal(err)
}
fmt.Println("Happy birthday,", adults[0].Name)
}
package main
import (
"context"
"fmt"
"log"
_ "github.com/jackc/pgx/v5/stdlib"
"github.com/skudra-go/ant"
"github.com/skudra-go/ant/dialect/postgres"
)
type User struct {
ant.Base // ID, CreatedAt, UpdatedAt
Name string
Email string `ant:"unique"`
Age int
Posts []Post // found through Post.UserID
}
type Post struct {
ant.Base
UserID int64
Title string
}
type AppDB struct {
ant.Context
Users ant.Table[User]
Posts ant.Table[Post]
}
var Users = ant.Fields[User]()
func main() {
ctx := context.Background()
dsn := "postgres://postgres:hello@127.0.0.1:5432/postgres"
db, err := ant.Open[AppDB](ctx, postgres.Dialect, dsn)
if err != nil {
log.Fatal(err)
}
defer db.Close()
// Creates the tables if they're missing. Real projects use migrations.
if err := db.EnsureCreated(ctx); err != nil {
log.Fatal(err)
}
// Insert Alice and her posts on the first run, and find her on later ones.
alice, created, err := db.Users.FirstOrCreate(ctx, &User{
Name: "Alice",
Email: "alice@example.com",
Age: 30,
Posts: []Post{{Title: "Hello"}, {Title: "Second post"}},
}, ant.Eq(&Users.Email, "alice@example.com"))
if err != nil {
log.Fatal(err)
}
if created {
fmt.Println("Created", alice.Name)
}
// Load every adult with their posts.
adults, err := db.Users.
Where(ant.Gte(&Users.Age, 18)).
Include(&Users.Posts).
OrderBy(&Users.Name).
All(ctx)
if err != nil {
log.Fatal(err)
}
for _, u := range adults {
fmt.Printf("%s is %d and has %d posts\n", u.Name, u.Age, len(u.Posts))
}
// Change a loaded user and save.
adults[0].Age++
err = db.SaveChanges(ctx)
if err != nil {
log.Fatal(err)
}
fmt.Println("Happy birthday,", adults[0].Name)
}
Run it
go mod tidy
go run .
Created Alice
Alice is 30 and has 2 posts
Happy birthday, Alice
A second run finds Alice and prints the age the first run saved:
Alice is 31 and has 2 posts
Happy birthday, Alice
The rows are in the database:
- SQLite
- PostgreSQL
sqlite3 hello.db 'SELECT id, name, age FROM users'
docker exec hello-db psql -U postgres -c 'SELECT id, name, age FROM users'
id | name | age
----+-------+-----
1 | Alice | 32
What each step sent
- SQLite
- PostgreSQL
ant.Raw ran the two CREATE TABLE statements in main.go.
FirstOrCreate found no user with that email on the first run. It inserted Alice, then both posts in one statement with her new key as user_id:
SELECT "users"."id", "users"."created_at", "users"."updated_at", "users"."name", "users"."email", "users"."age" FROM "users" WHERE "users"."email" = ? LIMIT ?
INSERT INTO "users" ("created_at", "updated_at", "name", "email", "age") VALUES (?, ?, ?, ?, ?) RETURNING "id"
INSERT INTO "posts" ("created_at", "updated_at", "user_id", "title") VALUES (?, ?, ?, ?), (?, ?, ?, ?) RETURNING "id"
Include loaded every user's posts in one query:
SELECT "users"."id", "users"."created_at", "users"."updated_at", "users"."name", "users"."email", "users"."age" FROM "users" WHERE "users"."age" >= ? ORDER BY "users"."name"
SELECT "posts"."id", "posts"."created_at", "posts"."updated_at", "posts"."user_id", "posts"."title" FROM "posts" WHERE "posts"."user_id" IN (?)
SaveChanges compared Alice with the copy ant kept at load time. It wrote only age and the timestamp:
UPDATE "users" SET "age" = ?, "updated_at" = ? WHERE "users"."id" = ?
EnsureCreated (PostgreSQL only) created the missing tables from the structs. On later runs it does nothing. It's for tests and prototypes, so use migrations for a real schema.
CREATE TABLE "users" (
"id" bigint GENERATED BY DEFAULT AS IDENTITY,
"created_at" timestamptz NOT NULL,
"updated_at" timestamptz NOT NULL,
"name" text NOT NULL,
"email" text NOT NULL,
"age" bigint NOT NULL,
CONSTRAINT "users_pkey" PRIMARY KEY ("id"),
CONSTRAINT "users_email_key" UNIQUE ("email")
)
-- and "posts", an index on "posts"."user_id", and its foreign key
FirstOrCreate found no user with that email on the first run. It inserted Alice, then both posts in one statement with her new key as user_id:
SELECT ... FROM "users" WHERE "users"."email" = $1 LIMIT $2
INSERT INTO "users" ("created_at", "updated_at", "name", "email", "age") VALUES ($1, $2, $3, $4, $5) RETURNING "id"
INSERT INTO "posts" ("created_at", "updated_at", "user_id", "title") VALUES ($1, $2, $3, $4), ($5, $6, $7, $8) RETURNING "id"
Include loaded every user's posts in one query:
SELECT ... FROM "users" WHERE "users"."age" >= $1 ORDER BY "users"."name"
SELECT ... FROM "posts" WHERE "posts"."user_id" IN ($1)
SaveChanges compared Alice with the copy ant kept at load time. It wrote only age and the timestamp:
UPDATE "users" SET "age" = $1, "updated_at" = $2 WHERE "users"."id" = $3
&Users.Age is a field pointer for the age column. A misspelled field doesn't compile.
Start over
- SQLite
- PostgreSQL
rm hello.db
To delete the database and its data:
docker rm -f hello-db
Next
- Concepts: the ideas behind the program above.
- Migrations: replace
EnsureCreatedwith SQL files you review. - Example projects: this program, a blog API, an audit service and a ledger.
- AI assistants: give Claude, Codex, Cursor or Copilot the docs, so they write ant and not GORM.