Skip to main content

Errors

Match errors with errors.Is and errors.As, never by their text. Builders collect errors while you chain. The call that runs the query returns them, joined if there are several.

user, err := db.Users.Find(ctx, id)

if errors.Is(err, ant.ErrNotFound) {
return nil
}

Reading rows​

ErrorMeans
ant.ErrNotFoundFirst, Single, Find or Reload found no row
ant.ErrMultipleRowsSingle found more than one
ant.ErrUnknownColumnA result column has no field, under WithStrict
ant.ErrCursorA page cursor this query cannot use
ant.ErrIncludeInEachEach with Include, which would need a second query while rows stream. Use All, or Chunk
ant.ErrIncludeInSubqueryA subquery with Include
ant.ErrNoColumnsA query whose selection leaves no columns

Writing rows​

ErrorMeans
ant.ErrNoConditionA bulk write with no condition that can exclude a row. Unfiltered allows it on purpose
ant.ErrNoAssignmentAn Update with nothing to set
ant.ErrNoRowsA write given no rows
ant.ErrNilEntityA nil pointer passed to a write
ant.ErrReadOnlyA write to a read-only model, such as a view
ant.ErrNotSoftDeletedRestore on a model with no DeletedAt
ant.ErrNotManyToManyLink or Unlink on another kind of relation
ant.ErrCycleNew entities that depend on each other, so neither can be inserted first. Save them in two steps

Using the wrong field or key​

ErrorMeans
ant.ErrNotProbeA pointer that does not come from a probe
ant.ErrWrongModelA field pointer from another model's probe
ant.ErrNotColumnA relation used as a column
ant.ErrNotRelationA field that is not a relation, used as one
ant.ErrNoKeyA key operation on a model with no primary key
ant.ErrKeyTypeA key whose type does not match the primary key

antvet finds most of these at build time.

Setup​

ErrorMeans
ant.ErrNoContextThe type passed to Open does not embed ant.Context
ant.ErrNotOpenA table or context that did not come from Open
ant.ErrNoForeignKeyA relation whose foreign key cannot be found by convention. Name it in Configure
ant.ErrNoColumnTypeA field whose database type cannot be worked out. Set it with Column(...).Type(...)
ant.ErrBadSchemaModels that cannot become a valid schema
ant.ErrNotImplementedA feature with no implementation yet

Change tracking and transactions​

ErrorMeans
ant.ErrConcurrencyA version or token check failed. See stale writes
ant.ErrConcurrentUseA context with change tracking was used by two operations at once. See a tracking context used twice
ant.ErrKeyChangedThe primary key of a tracked entity was changed. Insert a new entity instead
ant.ErrNotTrackedAn operation on an entity the context does not track
ant.ErrNotInTxCommit, Rollback or a savepoint outside a transaction
ant.ErrTxDoneThe transaction already ended
ant.ErrTxTypeA Tx closure whose parameter is not this context's type

Stale writes​

ant.ErrConcurrency comes back from SaveChanges and from an Upsert of a copy that carries a version, on every database including MySQL and MariaDB. It is an *ant.ConcurrencyError naming the row:

_, err := db.Pages.Upsert(ctx, stale, ant.OnConflict(&Pages.Slug))

var conflict *ant.ConcurrencyError

if errors.As(err, &conflict) {
fmt.Println(conflict.Model, conflict.Key)
}

A tracking context used twice​

If a second operation starts on a tracking context while the first runs, the second gets ant.ErrConcurrentUse at once without waiting. Give each request its own ant.Session, or share a context opened with WithTracking(false). A query that a hook makes must use the context.Context the hook received. See sessions and hooks.

Unsupported on this database​

ant.ErrUnsupported means the connected database cannot do what you asked. ant refuses before sending SQL.

_, err := ant.Merge(&db.Users, db.Posts.Query(), ant.EqCol(&Users.ID, &Posts.UserID)).
WhenMatched(ant.Set(&Users.Age, 1)).
Exec(ctx)
// ant: not supported by this database: MERGE on mysql

Cases beyond the feature table in databases:

Check first:

if dialect.Supports(db.Dialect(), dialect.Merge) {
// ...
}

Naming a column twice​

PostgreSQL and SQL Server refuse a write that gives a column two values. MySQL keeps the last. ant refuses it before any SQL runs, on every database. It covers DoUpdate and Set of an upsert, a bulk Update, UpdateMany, a merge's WhenMatched and WhenNotMatched, and the mappings of InsertFrom.

_, err := db.Users.Where(ant.Eq(&Users.ID, id)).Update(ctx, ant.Set(&Users.Name, "x"), ant.Set(&Users.Name, "y"))
// ant: User.Name has two assignments; give it one

Naming a version field in any of those is refused too, since ant moves it on by itself. UpdatedAt is the exception: the value you give wins over ant's.

Validation errors​

A failed field rule is an *ant.ValidationError with Model, Field and Err. It unwraps to the rule's error.

Database errors​

These classify a database's error on all five databases.

err := db.Users.Insert(ctx, user)

switch {
case ant.IsUniqueViolation(err):
return errors.New("already exists")
case ant.IsForeignKeyViolation(err):
return errors.New("refers to something missing")
case ant.IsNotNullViolation(err), ant.IsCheckViolation(err):
return errors.New("invalid")
case ant.IsRetryable(err):
return errors.New("try again")
}

ant.SQLState(err) returns the code itself, such as 23505. Each dialect translates its own codes.

FunctionSQLSTATE
ant.IsUniqueViolation23505
ant.IsForeignKeyViolation23503
ant.IsNotNullViolation23502
ant.IsCheckViolation23514
ant.IsRetryable40001 (serialization failure) and 40P01 (deadlock)

IsRetryable is true for MySQL and MariaDB deadlocks, and for MariaDB error 1020, which MariaDB 11.6 and later raise when a row changed since the transaction's snapshot. MariaDB rolls the transaction back, so run it again from the start.

Retry a transaction​

func transfer(ctx context.Context, db *AppDB) error {
var err error

for range 3 {
err = db.Tx(ctx, func(tx *AppDB) error {
// ... reads and writes
return nil
})

if !ant.IsRetryable(err) {
return err
}
}

return err
}

Find the failing statement​

ant.FailedSQL returns the statement behind a query error, with placeholders and no values, so it is safe for an internal log.

err := db.Users.Insert(ctx, user)

slog.Error("insert failed", "sql", ant.FailedSQL(err))

ant.WithDetailedErrors() adds the statement to every error's message. Leave it off where errors reach users. A database error's message can also quote a value, so do not return err.Error() to a client.

Strict scanning​

By default a result column with no field is ignored. ant.WithStrict() returns ant.ErrUnknownColumn instead.

db, err := ant.Open[AppDB](ctx, postgres.Dialect, dsn, ant.WithStrict())

ant.WithLooseScan() switches WithStrict back off, for code that builds options in layers.