Description
I've searched through your source code and documentation but I cannot find a solution.
I want to select an entry as well as for all entries in another table that are related to it.
A simplified example would like this:
-- schema.sql
CREATE TABLE authors (
id BIGSERIAL PRIMARY KEY,
name TEXT NOT NULL
);
CREATE TABLE books (
id BIGSERIAL PRIMARY KEY,
author_id BIGINT NOT NULL REFERENCES authors(id),
title TEXT NOT NULL
);
-- query.sql
-- name: GetAuthorsWithBooks :many
SELECT a.id,
a.name,
jsonb_agg(jsonb_build_object('id',
b.id,
'author_id',
b.author_id,
'title',
b.title,)
) FILTER (WHERE b.id IS NOT NULL)
AS books
FROM authors a
LEFT JOIN books b
ON a.id = b.author_id
GROUP BY a.id;
I would like to produce a result model similiar to this example:
type GetAuthorsWithBooks struct {
ID int64 `db:"id" json:"id"`
Name string `db:"name" json:"name"`
// I would like to get this generated attribute
Books []Book `db:"books" json:"books"`
// But instead i get this
Books []byte `db:"books" json:"books"`
}
type Book struct {
ID int64 `json:"id"`
AuthorID int64 `json:"author_id"`
Title string `json:"title"`
}
I tried to use overrides to achieve the desired result model and these overrides work when configured by type but not by column name:
version: "2"
sql:
- schema: "internal/db/schema.sql"
queries: "internal/db/query.sql"
engine: "postgresql"
gen:
go:
package: "dbgen"
out: "internal/db/gen"
emit_db_tags: true
emit_json_tags: true
json_tags_id_uppercase: false
json_tags_case_style: snake
overrides:
- db_type: json # This one works but overrides all json columns to books which interferes with other queries.
go_type:
type: "Book"
slice: true
- column: "GetAuthorsWithBooks.books" # This config is not documented but I did not know what else to use as the correct table name.
go_type:
type: "Book"
slice: true
It does not work and does not produce any errors or something else (version 1.29). It just gets ignored as far as I can tell.
Does anyone of a way to archive this without using (materialized) views? Just with plain sqlc?
Or if not does anyone know a way to override a type for a column that is not an existing column in an existing table?
I mean when I would run SELECT now()::timestamptz AS current_time
what would I have to fill in here:
sql:
- gen:
go:
overrides:
- column: "what use here?" # I know you would use override by type here but how would I override this column by name?
go_type:
import: time
type: Time