Skip to main content

Reading rows

A query runs when you call one of these.

Get every matching row​

All returns the rows as []*T. No matches is an empty slice, not an error.

users, err := db.Users.Where(ant.Gt(&Users.Age, 18)).All(ctx)
// SELECT ... FROM "users" WHERE "users"."age" > $1

Get the first row​

First returns one row, or ant.ErrNotFound. Order the query to say which row is first.

oldest, err := db.Users.OrderByDesc(&Users.Age).First(ctx)
// SELECT ... FROM "users" ORDER BY "users"."age" DESC LIMIT $1

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

Get the one row that must exist​

Single expects exactly one row. It returns ant.ErrNotFound for none and ant.ErrMultipleRows for more than one.

user, err := db.Users.Where(ant.Eq(&Users.Email, "ada@example.com")).Single(ctx)
// SELECT ... FROM "users" WHERE "users"."email" = $1 LIMIT $2 -- $2 = 2

It asks for two rows so it can tell one from many.

Find by primary key​

Find returns the row with that key, or ant.ErrNotFound. For a composite key, use FindKey.

user, err := db.Users.Find(ctx, id)
// SELECT ... FROM "users" WHERE "users"."id" = $1 LIMIT $2

With tracking on, a Find for a row the context already tracks sends no query and returns the tracked instance, unsaved changes included.

Stream a large result​

Each is a Go iterator that yields rows one at a time. break releases the connection.

for user, err := range db.Users.OrderBy(&Users.Name).Each(ctx) {
if err != nil {
return err
}

fmt.Println(user.Name)
}
// SELECT ... FROM "users" ORDER BY "users"."name"

A query error arrives as the only item. Each rows aren't tracked, and Each refuses Include with ant.ErrIncludeInEach. To process a large result in batches with Include, use Chunk.

Count and check​

Count returns the number of matching rows. Exists and DoesNotExist answer without fetching rows.

n, err := db.Users.Where(ant.Gt(&Users.Age, 18)).Count(ctx)
// SELECT COUNT(*) FROM "users" WHERE "users"."age" > $1

found, err := db.Users.Where(ant.Eq(&Users.Name, "Ada")).Exists(ctx)
// SELECT EXISTS (SELECT 1 FROM "users" WHERE "users"."name" = $1)

missing, err := db.Users.Where(ant.Eq(&Users.Name, "Ada")).DoesNotExist(ctx)

Count honors Limit, Offset and Distinct by counting the rows of the limited query:

n, err := db.Users.OrderBy(&Users.Name).Limit(5).Count(ctx)
// SELECT COUNT(*) FROM (SELECT ... FROM "users" LIMIT $1) AS "ant_counted"

On a query built with FromCTE or Recursive, Count and Exists write the WITH at the start of the statement on every database, because SQL Server takes it nowhere else. See CTEs.

Read one column​

ant.Pluck reads a single column into a slice of its Go type.

names, err := ant.Pluck(ctx, db.Users.Where(ant.Gte(&Users.Age, 18)).OrderBy(&Users.Name), &Users.Name)
// SELECT "users"."name" FROM "users" WHERE "users"."age" >= $1 ORDER BY "users"."name"

With a pointer column, NULLs come back as nil:

bios, err := ant.Pluck(ctx, db.Users.Where(), &Users.Bio) // []*string
// SELECT "users"."bio" FROM "users"

Load part of a row​

Column and Omit load only some columns. The other fields keep their zero value, so these rows are never tracked and can't be saved by mistake.

names, err := db.Users.Column(&Users.ID).Column(&Users.Name).All(ctx)
// SELECT "users"."id", "users"."name" FROM "users"

small, err := db.Users.Omit(&Users.Bio).All(ctx)
// SELECT "users"."id", "users"."created_at", "users"."updated_at", "users"."name", "users"."email", "users"."age" FROM "users"

For results in a shape of your own, see projections.

Distinct values​

ages, err := db.Users.Column(&Users.Age).Distinct().All(ctx)
// SELECT DISTINCT "users"."age" FROM "users"

Skip the tracker​

Results are tracked by default so SaveChanges can see your changes. NoTracking skips the snapshot.

users, err := db.Users.NoTracking().Where(ant.Gt(&Users.Age, 18)).All(ctx)

On 1000 rows that's 1.2 times faster and half the memory (benchmarks).

NoTrackingResolved skips it too but still gives each row a single instance.

One tracking context, one operation at a time​

A tracked read, Find included, claims the tracker. A second one that starts before the first ends returns ant.ErrConcurrentUse instead of waiting.

Give each request or goroutine its own context with ant.Session. A context opened with ant.WithTracking(false) never claims, so it is safe to share.

func handler(w http.ResponseWriter, r *http.Request) {
db := ant.Session(shared) // its own tracker

users, err := db.Users.Where(ant.Gt(&Users.Age, 18)).All(r.Context())
// ...
}

Chunk claims the tracker for one batch at a time and lets go before it calls your function, so the function can run queries on the same context. A hook that queries must pass on the context.Context it was given, so its query counts as part of the operation that ran it.