Bulk writes
These calls skip the model layer. They run no hooks, track nothing, and write relations only when you do it yourself.
Insert many rows
InsertMany writes rows in multi-row statements inside one transaction and returns how many went in. Generated keys are copied back onto your structs.
n, err := db.Users.InsertMany(ctx, users, ant.BatchSize(500))
// INSERT INTO "users" (...) VALUES ($1, ...), ($7, ...), ... RETURNING "id"
A batch holds 1,000 rows unless you set ant.BatchSize. ant also splits a batch to fit the database's parameter limit, so a size larger than one statement can take still works. The keys are cleared if it fails.
InsertMany ignores relation fields. To save a graph, use Insert.
Skip rows that already exist
ant.WithConflict applies a conflict clause to every row. With DoNothing, rerunning an import inserts only the new rows:
n, err := db.Users.InsertMany(ctx, users, ant.WithConflict(ant.OnConflict(&Users.Email).DoNothing()))
// INSERT INTO "users" (...) VALUES ($1, ...), ($7, ...) ON CONFLICT ("email") DO NOTHING
n counts the rows written. Skipped rows may leave their structs without a key, so keys are not copied back when a conflict clause is set.
With DoUpdate or Set, existing rows are updated instead. A model with a version increments it for each row updated, and InsertMany doesn't check it. See upsert.
On MySQL and MariaDB, rows with generated keys go in one statement each, since the key comes from LastInsertId. See databases.
Update many rows
UpdateMany writes a different value per row, for the columns you name, one UPDATE per row in a single transaction. Other fields are left alone. As a bulk Update does, it stamps UpdatedAt unless you name it, moves a version column on, and skips rows the model's filters leave out, such as soft-deleted ones. Name each column once; naming one twice returns an error before anything runs.
alice.Age, bob.Age = 31, 18
n, err := db.Users.UpdateMany(ctx, []*User{alice, bob}, ant.F(&Users.Age))
// UPDATE "users" SET "age" = $1, "updated_at" = $2 WHERE "users"."id" = $3 -- once per row
When every row gets the same value or an expression, a bulk Update is one statement.
Tracked entities keep their snapshots, so use SaveChanges for them.
Copy rows inside the database
InsertFrom copies rows with one INSERT ... SELECT, so the data never reaches your program. ant.Into maps a column to a source field, and ant.IntoExpr to an expression.
type Archive struct {
ID int64
Title string
Tag string
}
var Archives = ant.Fields[Archive]()
n, err := db.Archives.InsertFrom(ctx, ant.Project[Archive](
db.Posts.Where(ant.Eq(&Posts.Published, true)),
ant.Into(&Archives.Title, &Posts.Title),
ant.IntoExpr(&Archives.Tag, ant.SQL[string]("'archived'")),
))
// INSERT INTO "archives" ("title", "tag")
// SELECT "posts"."title" AS "title", 'archived' AS "tag"
// FROM "posts" WHERE "posts"."published" = $1
Mapping one column twice returns an error before anything runs.
Empty a table
Truncate empties a table, faster than Delete. It fails on a table others still refer to. It doesn't clear the tracker, so call db.ClearTracked(ctx) if you hold these rows.
err := db.Posts.Truncate(ctx)
COPY on PostgreSQL
pgxext.Copy loads rows through PostgreSQL's COPY, the fastest way in for large files. Timestamps are filled in, but keys from the database don't come back. It needs the pgx driver.
n, err := pgxext.Copy(ctx, db, users)
Batches in one round trip
pgxext.Batch sends several statements together, as one transaction, so a failure undoes all of them. UpdateSQL and DeleteSQL build a statement without running it.
var batch pgxext.Batch
batch.Add(db.Users.Where(ant.Eq(&Users.ID, alice.ID)).UpdateSQL(ctx, ant.Set(&Users.Age, 41)))
batch.Add(db.Users.Where(ant.Eq(&Users.ID, bob.ID)).DeleteSQL(ctx))
batch.Exec("UPDATE users SET age = age + 1 WHERE id = $1", alice.ID)
affected, err := batch.Send(ctx, db)
Copy and Batch.Send take a pool connection of their own, so they can't join a transaction: given a transaction's context, such as one inside db.Tx or anttest.Isolate, they return pgxext.ErrInTx rather than write rows that would survive its rollback.
affected holds the rows each statement touched.
See it tested: tests/features/writing/bulk_test.go