sqlc icon indicating copy to clipboard operation
sqlc copied to clipboard

MIN() returns an interface{}

Open abh opened this issue 3 years ago • 5 comments

Version

Other

What happened?

(version 1.16.0)

select min(id) from authors; creates a function that returns an interface{} instead of a NULL-able version of the id type.

#1574 talks about this for DATETIME types, but other issues indicates that it should work for simpler types, maybe?

If not, what's the workaround? Parsing the interface{} is awkward, best I can tell.

Relevant log output

No response

Database schema

No response

SQL queries

No response

Configuration

No response

Playground URL

https://play.sqlc.dev/p/96e9cf0291f2e13cc784144f8abd4d5a556c549f2bfe909a26377703f671ff61

What operating system are you using?

macOS

What database engines are you using?

MySQL

What type of code are you generating?

Go

abh avatar Nov 23 '22 08:11 abh

You can avoid this by casting a typecast. A PostgreSQL example is below.

-- name: GetMinID :one
select min(id)::BIGINT from authors;

Explicit typecasting will generate the intended code.

func (q *Queries) GetMinID(ctx context.Context) (int64, error) {
	row := q.db.QueryRowContext(ctx, getMinID)
	var column_1 int64
	err := row.Scan(&column_1)
	return column_1, err
}

In v1.16.0, aggregate functions such as MIN() and MAX() are not capable of generating fields of type depending on the column.

d-tsuji avatar Nov 23 '22 10:11 d-tsuji

@d-tsuji I'm using MySQL for this project and the equivalent features (CAST(foo as BIGINT)) don't seem to be implemented.

abh avatar Dec 19 '22 10:12 abh

This is still an issue in v1.18.0: https://play.sqlc.dev/p/3931aa6d071068031e5eb03f4e40bd474d22afb2e47aabe0c34e68101e76d2f1.

There is already an issue open for adding CAST support: https://github.com/kyleconroy/sqlc/issues/687

andrewmbenton avatar Jun 06 '23 18:06 andrewmbenton

It didn't work for my actual use case, but I noticed that in a simple use case doing a sub-select sometimes(?) makes sqlc figure out the correct type.

select id from (select min(id) from authors) as min_author;

https://play.sqlc.dev/p/e4b7f02a9c2ab5a4cea69f216758eb0d0a9ba42576804548e4f45b8c47e79910

abh avatar Jul 18 '23 09:07 abh

The workaround I use is to add the result to 0. SELECT 0 + count(value) FROM table; gets correctly recognized as an int.

sknig avatar Jun 08 '25 11:06 sknig