Upsert and merge
Upsert inserts a row, or applies your conflict instructions when a unique constraint finds it already there. Merge covers what an upsert can't, such as deleting rows in the same statement.
Upsert
user := &User{
Name: "Ada",
Email: "ada@example.com",
Age: 36,
}
wrote, err := db.Users.Upsert(ctx, user, ant.OnConflict(&Users.Email))
// INSERT INTO "users" ("created_at", "updated_at", "name", "email", "age", "bio")
// VALUES ($1, $2, $3, $4, $5, $6)
// ON CONFLICT ("email") DO UPDATE SET
// "name" = "excluded"."name", "age" = "excluded"."age", "bio" = "excluded"."bio",
// "updated_at" = $7
// RETURNING "id", "created_at", "updated_at", "name", "email", "age", "bio"
OnConflict names the unique column. By default every column except the key, the constraint's own and CreatedAt is overwritten, and your struct receives the stored row, key included. A zero value overwrites too. UpdatedAt takes the current time on the update branch of every upsert, unless the clause assigns it.
Running it twice leaves one row, so a feed can be reapplied after a crash and changed rows are updated.
An upsert offers your struct as a new row, so it checks the validation rules and runs Validate, BeforeInsert and AfterInsert whichever way the database goes, as GORM runs its create hooks. If the transaction around it rolls back, the struct loses the key it was given and stops being tracked, as after a rolled-back Insert.
Choose what changes
onEmail := ant.OnConflict(&Users.Email)
wrote, err := db.Users.Upsert(ctx, user, onEmail.DoUpdate(ant.F(&Users.Age)))
// ... ON CONFLICT ("email") DO UPDATE SET "age" = "excluded"."age", "updated_at" = $7
Set assigns values, including ones based on the existing row. Here the first call inserts the row at 1 and later calls add 1.
type Hit struct {
ID int64
Path string `ant:"unique"`
Count int
}
var Hits = ant.Fields[Hit]()
hit := &Hit{Path: "/home", Count: 1}
wrote, err := db.Hits.Upsert(ctx, hit, ant.OnConflict(&Hits.Path).Set(ant.Inc(&Hits.Count, 1)))
// INSERT INTO "hits" ("path", "count") VALUES ($1, $2)
// ON CONFLICT ("path") DO UPDATE SET "count" = ("hits"."count" + $3)
// RETURNING "id", "path", "count"
The insert and the increment are one statement, so concurrent requests don't lose a count.
Naming a field twice, in DoUpdate, Set, or both, returns an error before anything runs.
Skip existing rows
DoNothing keeps the existing row and reports false, leaving your struct as it was.
wrote, err := db.Users.Upsert(ctx, user, ant.OnConflict(&Users.Email).DoNothing())
// ... ON CONFLICT ("email") DO NOTHING RETURNING ...
A key on several columns
And adds a column for a multi-column constraint.
conflict := ant.OnConflict(&Users.Email).And(ant.F(&Users.Name))
// ON CONFLICT ("email", "name")
Upsert many rows
InsertMany takes a conflict too, with one statement per batch:
n, err := db.Users.InsertMany(ctx, users, ant.WithConflict(ant.OnConflict(&Users.Email).DoUpdate(ant.F(&Users.Age))))
// INSERT INTO "users" (...) VALUES ($1, ...), ($7, ...)
// ON CONFLICT ("email") DO UPDATE SET "age" = "excluded"."age", "updated_at" = $13
Rows that conflict may be skipped, so InsertMany doesn't copy keys back when it has a conflict clause.
Versioned rows
On a model with a version field, every write that updates a row increments the version: Upsert, DoUpdate, Set, Merge, and InsertMany with a conflict. A new row starts at 1.
// ... ON CONFLICT ("title") DO UPDATE SET "views" = "excluded"."views",
// "version" = ("docs"."version" + 1)
Naming the version in DoUpdate, Set, or a Merge assignment is an error before anything runs.
An entity with a version of its own is a loaded copy, so Upsert applies its update only while the stored row still has that version. Otherwise it returns an *ant.ConcurrencyError, which matches ant.ErrConcurrency, as SaveChanges does. A zero version means a new entity and is not checked.
doc := &Doc{Title: "T", Views: 3, Version: 1}
_, err := db.Docs.Upsert(ctx, doc, ant.OnConflict(&Docs.Title))
// ... ON CONFLICT ("title") DO UPDATE SET ..., "version" = ("docs"."version" + 1)
// WHERE "docs"."version" = $6
// errors.Is(err, ant.ErrConcurrency) when the stored version is not 1
InsertMany can't tell a row's own version from the 1 it gives a new row, so it moves versions on and doesn't check them.
MySQL and MariaDB have no condition on ON DUPLICATE KEY UPDATE, so ant guards each assignment instead: col = CASE WHEN version = ? THEN new ELSE col END. A stale copy changes nothing and gets the same error. This reads the affected-row count, so keep the driver's clientFoundRows option off, which is its default.
On MySQL and MariaDB
ON DUPLICATE KEY has no target, so any unique key triggers it, not only the columns you name. If a different key is the one that collides, Upsert can't find the row by your columns, and reports that it wrote nothing. Name the only unique key that can collide.
MySQL refuses an upsert whose Set reads its own table, so ant writes the rows as INSERT ... SELECT. A SELECT has no DEFAULT, so InsertMany with a column left to its default and such a Set returns ant.ErrUnsupported. See databases.
SQL Server has no upsert. Use ant.Merge.
Merge
ant.Merge decides, row by row, what a batch of source rows does to a table. One statement can update, insert, and delete. Clauses run in the order you add them, and the first one that fits a row wins. It needs PostgreSQL 15 or SQL Server, and returns ant.ErrUnsupported elsewhere.
type Stock struct {
ID int64
SKU string `ant:"unique"`
Count int
}
type Staged struct {
ID int64
SKU string
Count int
}
var (
Stocks = ant.Fields[Stock]()
Stageds = ant.Fields[Staged]()
)
changed, err := ant.Merge(&db.Stock, db.Staged.Query(), ant.EqCol(&Stocks.SKU, &Stageds.SKU)).
WhenMatchedIf(ant.Eq(&Stageds.Count, 0)).Delete().
WhenMatched(ant.SetExpr(&Stocks.Count, ant.Col(&Stageds.Count))).
WhenNotMatched(ant.Into(&Stocks.SKU, &Stageds.SKU), ant.Into(&Stocks.Count, &Stageds.Count)).
Exec(ctx)
// MERGE INTO "stocks"
// USING (SELECT "stageds"."id", "stageds"."sku", "stageds"."count" FROM "stageds") AS "stageds"
// ON ("stocks"."sku" = "stageds"."sku")
// WHEN MATCHED AND "stageds"."count" = $1 THEN DELETE
// WHEN MATCHED THEN UPDATE SET "count" = "stageds"."count"
// WHEN NOT MATCHED THEN INSERT ("sku", "count") VALUES ("stageds"."sku", "stageds"."count")
Exec returns the rows changed. A merge is a bulk write: it loads no entities, so no hooks or validation rules run.
What Merge fills in
Merge builds its statement from what you give it, then adds what Insert and Update add. A matched update sets UpdatedAt. An insert sets CreatedAt, UpdatedAt, the version, and the model's discriminator. A mapping you give for one of these columns wins. On a stock model that has timestamps and a version, the statement above becomes:
// WHEN MATCHED THEN UPDATE SET "count" = "stageds"."count", "updated_at" = $2,
// "version" = ("stocks"."version" + 1)
// WHEN NOT MATCHED THEN INSERT ("sku", "count", "version", "created_at", "updated_at")
// VALUES ("stageds"."sku", "stageds"."count", 1, $3, $4)
A key from a Go generator is not filled, because one statement inserts many rows. Map the key from the source, or let the database generate it.
As with other writes, a column can have one assignment per clause, and naming the version is an error.
On SQL Server, ant writes the statement WITH (HOLDLOCK), because without it two concurrent merges can both find no row and both insert it. On PostgreSQL, a merge that inserts a row another one inserted meanwhile fails with a unique violation for the application to retry. Upsert has no such failure there.
See it tested: tests/features/writing/upsert_test.go