sqlc icon indicating copy to clipboard operation
sqlc copied to clipboard

SELECT foo.id AS foo_id loses Go type information

Open tv42 opened this issue 5 years ago • 7 comments

I'm trying to use custom Go types for some SQL columns, mapping a sql int64 to Go type FooID uint64.

It seems I can have

SELECT foo.id FROM ... and get generated type FooRow struct { ID FooID }

or I can have

SELECT foo.id AS foo_id FROM ... and get type FooRow struct { FooID int64 }

but I cannot get both at the same time. Using the AS forgets the association with the Go type, but without the AS my struct fields are kinda misleading. Consider SELECT foo.id, bar.id FROM ..., can't have two things fighting for the struct field name ID.

tv42 avatar Jul 21 '20 20:07 tv42

@tv42 Can you provide a complete example for this issue? Since this involves type overrides, can you include a sqlc configuration file, database schema, and example queries.

kyleconroy avatar Aug 28 '21 21:08 kyleconroy

Here's a full repro with the latest versions: https://gist.github.com/tv42/34d87e0975739f20654eac4894380511

To summarize:

-- name: BadType :one
SELECT users.id AS user_id, 42 as filler FROM users LIMIT 1;

-- name: BadName :one
SELECT users.id, 42 as filler FROM users LIMIT 1;
    overrides:
      - column: users.id
        go_type: example.com/sqlc_issues606_reproducer.UserID

How it goes wrong:

$ go generate
$ grep -A 1 'type Bad' query.sql.go
type BadNameRow struct {
	ID     sqlc_issues606_reproducer.UserID
--
type BadTypeRow struct {
	UserID int64

tv42 avatar Aug 31 '21 15:08 tv42

Can you please re-open this? It's still there, as the previous comment shows.

tv42 avatar Sep 08 '21 18:09 tv42

@tv42 whoops, sorry about that. Thanks for writing up the full example.

kyleconroy avatar Sep 08 '21 23:09 kyleconroy

I've personally tested this one with sqlc v1.13.0 and with type overrides this can be easily worked around. Could that solve it @tv42 ?

alarbada avatar Apr 05 '22 12:04 alarbada

I've personally tested this one with sqlc v1.13.0 and with type overrides this can be easily worked around. Could that solve it @tv42 ?

Sorry that's too vague to say much. The reproducing example already uses type overrides to switch from an int64 to UserID, do you think it is somehow wrong?

    overrides:
      - column: users.id
        go_type: example.com/sqlc_issues606_reproducer.UserID

The bug seems to be that using SELECT column_name AS alias makes the type overrides not be applied.

tv42 avatar Apr 19 '22 15:04 tv42

I've also run into this issue. Here is my repro: https://gist.github.com/WesleyMiller1998/7730c3ab8b3183c432075728a4e463bf

It appears that a column override messes with the type generation. I may dig into the issue later and open a PR

WesleyMiller1998 avatar Jul 20 '22 22:07 WesleyMiller1998