Skip to content

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

@timflyio

Description

@timflyio

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions