sqlc-dev / sqlc

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

Redundant import of lib/pq when using sqlc.slice() with sqlc.narg() with MySQL #3420

Open dskarataev opened 3 months ago

dskarataev commented 3 months ago

Version

1.26.0

What happened?

When I run sqlc generate with engine: "mysql and I use sqlc.slice(myslice) inside queries, in the generated file with Go code it inserts an import of "github.com/lib/pq" but it is not used in any code so my app does not compile after that.

It happens only when I use it in combination with sqlc.narg(myslice) because I want to ensure that if the argument is null I do not need to filter by it.

The problem is reproducible in the online playground, please look at the link I've attached. Thanks!

Relevant log output

No response

Database schema

No response

SQL queries

No response

Configuration

No response

Playground URL

https://play.sqlc.dev/p/96994ab9c5be500a74b65ba1e9e870a7dce1fccfae8bc2956909cba197698c5f

What operating system are you using?

macOS

What database engines are you using?

MySQL

What type of code are you generating?

Go

dskarataev commented 3 months ago

Also, could you please guide me maybe how could I use sqlc.slice() to filter by it only in case if there are some elements in the slice? I see the current version of the code generation replaces the slice to NULL in the final SQL, how to use it correctly in that case?

Should it be something like that?

where
    coalesce(name in (sqlc.slice(names)), true);
ScodroS commented 1 month ago

I came across the same problem. The workaround I've found (although I don't like it, it is the only way I've found so far) is to add a new parameter "filter_by_names" of boolean type that I'm using to check whether I need to filter using the IN operator (which will be true if len(names) > 0). So the condition will be something like:

sqlc.arg(filter_by_names) = false OR name in (sqlc.slice(names))
dskarataev commented 1 month ago

We use this workaround successfully

coalesce(name in (sqlc.slice(names)), true)

It does not filter by the slice in case if it is empty because sqlc.slice function returns null in that case and the result of the whole expression becomes true so the query understands there is no need for any filtering in that case.

Hope it helps.