Im using sqlc with postgres in my golang app. And i try to implement simple logic, that will returns to me array of products with nested array of product categories inside. I saw that question. But it doesn't help. Here is my tables:
create table products
(
id serial primary key,
title text unique not null,
url text
);
create table product_categories
(
id serial primary key,
title text unique not null,
product_id integer not null
constraint products_id_fk references products (id),
url text
);
Here is query:
select p.*, sqlc.embed(pc)
from products p
join product_categories pc on pc.product_id = p.id
and i expect generated struct like this:
type GetAllProductsAndSubcatsRow struct {
ID int32 `db:"id" json:"id"`
Title string `db:"title" json:"title"`
Url pgtype.Text `db:"url" json:"url"`
ProductCategory []ProductCategory `db:"product_category" json:"product_category"`
}
but i got:
type GetAllProductsAndSubcatsRow struct {
ID int32 `db:"id" json:"id"`
Title string `db:"title" json:"title"`
Url pgtype.Text `db:"url" json:"url"`
ProductCategory ProductCategory `db:"product_category" json:"product_category"`
}
can't figure out what am i do wrong?
upd.
@Fraser answer this is the expected way to fix that issue, but sqlc has own opinion about it :)
usign array_agg postgres function doesn't help much, because generated struct looks like this
type GetAllProductsAndSubcatsRow struct {
ID int32 `db:"id" json:"id"`
Title string `db:"title" json:"title"`
Url pgtype.Text `db:"url" json:"url"`
ProductCategory interface{} `db:"product_category" json:"product_category"`
}
The
sqlc.embed(pc)doesn't make sense in this context, it is for embedding a single struct, not for creating a slice of structs.To work around this issue you can create a view that creates the
product_categoriescolumn as a json type, then use theoverridesfeature of sqlc to cast this as a slice ofProductCategory. e.g.This simplifies the query to
Now you need to override the type of your
product_view.product_categoriescolumn in yoursqlc.(yaml|yml)orsqlc.jsonfile, I use json in this example.This should give you models like so, with the correct
[]ProductCategoryslice on theProductViewstruct.This should now be correctly scanned with the generated function which should look something like...
I created a working playground version of all this here https://play.sqlc.dev/p/6a5d01a67c3569b16c77a8a47ac893093ecffa6e1ef36ac569a6ef4dcf4aef90