Projections
A projection turns rows into a struct of your own, with Select or Project.
Select | Project | |
|---|---|---|
| Runs | In Go, once per row | In SQL |
| Fetches | Every column of each joined table | Only what you map |
| Can use | Any Go code | Columns and expressions |
Shape rows in Go with Select
Select takes a typed closure on a join. The closure runs in Go, so it can use any Go code. ant can't turn it into SQL.
type Summary struct {
Author string
Title string
}
summaries, err := db.Posts.
Join(&Posts.User).
Where(ant.Eq(&Posts.Published, true)).
Select(func(p *Post, u *User) Summary {
return Summary{u.Name, p.Title}
}).
All(ctx)
// SELECT "posts"."id", "posts"."created_at", ..., "users"."id", "users"."created_at", ...
// FROM "posts" JOIN "users" ON "posts"."user_id" = "users"."id"
// WHERE "posts"."published" = $1
The result has All, First and Each, and yields []Summary, not a slice of pointers.
Shape rows in SQL with Project
Project selects only the columns you map, so it's cheaper on wide tables. Each mapping is a pair of field pointers: the destination, then the source.
var Summaries = ant.Fields[Summary]()
summaries, err := ant.Project[Summary](
db.Posts.Join(&Posts.User).Where(ant.Eq(&Posts.Published, true)),
ant.Into(&Summaries.Author, &Users.Name),
ant.Into(&Summaries.Title, &Posts.Title),
).All(ctx)
// SELECT "users"."name" AS "author", "posts"."title" AS "title"
// FROM "posts" JOIN "users" ON "posts"."user_id" = "users"."id"
// WHERE "posts"."published" = $1
IntoExpr maps an expression. A column that can be NULL needs a nullable destination.
ant.Project[Summary](
db.Users.Where(ant.Eq(&Users.Name, "Bob")),
ant.IntoExpr(&Summaries.Author, ant.Upper(&Users.Name)),
)
// SELECT UPPER("users"."name") AS "author" FROM "users" WHERE "users"."name" = $1
Project is also how grouped results and window functions come back.
Add a computed field to whole models
To keep whole models and add a value to each, tag a field computed and fill it with With. It's never written.
type Author struct {
ID int64
Name string
Posts []Post
PostCount int64 `ant:"computed"`
}
var Authors = ant.Fields[Author]()
authors, err := db.Authors.
With(&Authors.PostCount, ant.CountRelated(&Authors.Posts)).
All(ctx)
See it tested: tests/features/relations/project_test.go