sqlc-dev / sqlc

Generate type-safe code from SQL
https://sqlc.dev
MIT License
13.52k stars 810 forks source link

Cast query result to existing type instead of creating a new one #2252

Open corpix opened 1 year ago

corpix commented 1 year ago

What do you want to change?

Say we have two queries with JOINs:

-- name: SelectOneFileByID :one 
SELECT f.id, f.name, b.size
  FROM file f
JOIN blob b
  ON f.blob_id == b.id
WHERE f.id == $1;

-- name: SelectOneFileByName :one 
SELECT f.id, f.name, b.size
  FROM file f
JOIN blob b
  ON f.blob_id == b.id
WHERE f.name == $1;

This will generate two structs in Go:

I want single type: SelectOneFile because struct's generated by sqlc are of same shape, no need to generate data-type per query, there should be a way to override this semantics. What could be done? I thought it could be done with plugin, but there are nearly zero docs about plugins and looking at code I don't think plugins could solve this because they are not middlewares in the "data transformation pipeline" (I would be happy if there is some place I could inject custom code to transform Go's AST considering some annotations in SQL for example)

What database engines need to be changed?

Postgresql

What programming language backends need to be changed?

Go

iamnoah commented 1 year ago

In the same boat. This following are valid SQL:

select (table_a.*)::table_b from table_a;
select (table_a.id, table_a.name, table_a.size)::table_b from table_a;

But generating go code from them produces a []interface[] result parameter. Seems like the cast could be a hint to use the model type for the other table.