sqlc-dev / sqlc

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

COALESCE doesn't appear to work within a CTE #3381

Open Bronya-Rand opened 5 months ago

Bronya-Rand commented 5 months ago

Version

1.26.0

What happened?

When creating WITH statements in SQL, I've noticed that if I was to use COALESCE within a WITH that updates data, that it would result in sqlc generate saying that the column does not exist even though it does exist within the table using psql.

Relevant log output

# package queries
sql/collections.sql:30:9: column "updated_at" does not exist

Database schema

id | user_id | name | description | created_at | updated_at

SQL queries

-- name: CollectionUpdate :one
WITH updated_collection AS (
    UPDATE user_collections
    SET
        collection_name = COALESCE(sqlc.narg(collection_name), collection_name),
        collection_description = COALESCE(sqlc.narg(collection_description), collection_description),
        is_public = COALESCE(sqlc.narg(is_public), is_public),
        updated_at = COALESCE(sqlc.narg(updated_at), CURRENT_TIMESTAMP)
    WHERE id = sqlc.arg(id)
    RETURNING id
), deleted_characters AS (
    DELETE FROM collection_characters
    WHERE collection_id = (SELECT id FROM updated_collection) AND character_id != ALL(sqlc.narg('character_ids')::uuid[])
    RETURNING *
)

INSERT INTO collection_characters (character_id, collection_id)
SELECT UNNEST(sqlc.narg('character_ids')::uuid[]), (SELECT id FROM updated_collection)
ON CONFLICT DO NOTHING
RETURNING *;

Configuration

version: "2"
sql:
  - schema: "./migrate/migrations/"
    queries: "./sql/"
    engine: "postgresql"
    gen:
      go:
        emit_interface: true
        package: "queries"
        out: "queries"
overrides:
  go: null
plugins: []
rules: []

Playground URL

No response

What operating system are you using?

Linux

What database engines are you using?

PostgreSQL

What type of code are you generating?

Go

Abdullah-AlAttar commented 4 months ago

Facing the same issue. did you find a solution/workaround?

orisano commented 4 months ago

Can this be reproduced in the playground: https://play.sqlc.dev/ ?