sqlc icon indicating copy to clipboard operation
sqlc copied to clipboard

sqlc generator bug in sqlc-go when using named parameters and slices

Open timflyio opened this issue 2 weeks ago • 0 comments

Version

1.30.0

What happened?

I put a working demonstration up at https://github.com/timflyio/sqlcbug .

There is a query generator bug when using slices and using sqlc.arg() or @ to name parameters, as in this example:

-- name: BrokenQuery :many
SELECT sqlc.embed(mytable)
FROM mytable
WHERE
    typ IN (sqlc.slice(types))
    AND (sqlc.arg(allnames) OR (name IN (sqlc.slice(names))));

When running q.BrokenQuery(ctx, []int64{1, 2}, false, []string{"name1"}), sqlc generates:

-- name: BrokenQuery :many
SELECT mytable.id, mytable.typ, mytable.name, mytable.val
FROM mytable
WHERE
    typ IN (?,?)
    AND (?2 OR (name IN (?)))

-- ARGS: [1 2 false name1]

Because the sqlc.arg(allnames) was translated into the fixed string ?2, but the generator generates two variables for typ IN (?,?) (the number of types passed in), the positional value ?2 is incorrect and should be changed to ?3 here.

Workaround

This problem can be avoided by avoiding named parameters:

-- name: FixedQuery :many
SELECT sqlc.embed(mytable)
FROM mytable
WHERE
    typ IN (sqlc.slice(types))
    AND (? OR (name IN (sqlc.slice(names))));

When running q.FixedQuery(ctx, []int64{1, 2}, false, []string{"name1"}), sqlc generates:

-- name: FixedQuery :many
SELECT mytable.id, mytable.typ, mytable.name, mytable.val
FROM mytable
WHERE
    typ IN (?,?)
    AND (? OR (name IN (?)))

-- ARGS: [1 2 false name1]

and the parameters are placed where they belong.

Relevant log output

POC at https://github.com/timflyio/sqlcbug

Database schema

POC at https://github.com/timflyio/sqlcbug has a schema in schema.sql.

SQL queries

POC at https://github.com/timflyio/sqlcbug has a full working example with queries in query.sql and actually run queries emitted when running `./cmd/main.go`.

Configuration

POC at https://github.com/timflyio/sqlcbug has a config in `./sqlc.yaml`

Playground URL

No response

What operating system are you using?

Linux

What database engines are you using?

SQLite

What type of code are you generating?

Go

timflyio avatar Dec 03 '25 03:12 timflyio