sqlc icon indicating copy to clipboard operation
sqlc copied to clipboard

How to reuse return types across queries

Open kahunacohen opened this issue 1 year ago • 4 comments

As I understand it the overrides key in the config yaml is relevent to individual column overrides.

What if I have two distinct queries, say ListSongs and SearchSongs, but they both return the same data. sqlc generates two different row structs that these return even though they have the same fields. I don't want to resort to using empty interfaces or generics in my client code. Is there a best-practice for this?

kahunacohen avatar Jun 23 '24 10:06 kahunacohen

I commented on an existing issue asking if someone could point me in the right direction and I might be willing to work on a PR. https://github.com/sqlc-dev/sqlc/issues/781

kahunacohen avatar Jun 26 '24 07:06 kahunacohen

I think the best practice is to have the 2 structs without any change, and if you want to wrap it (I'll explain in a bit why I think it's a bad idea) do it outside of the generated code.

Wrapping it under a single interface will lead to very awkward behavior in the generated code. In the case you change only one of the queries, it will generate an additional struct your code doesn't use, and isn't necessarily trivial to integrate to your existing code. The reverse operation will be just as awkward - having 2 existing queries suddenly return the same interface will delete the previously used interface, breaking your code.

Lastly, if you see absolutely no scenario you will change only one of the queries, you should consider to try and merge your 2 queries in the first place (godspeed dynamic queries:))

SockworkOrange avatar Jun 28 '24 17:06 SockworkOrange

up

iceteahh avatar Mar 20 '25 05:03 iceteahh