sqlc icon indicating copy to clipboard operation
sqlc copied to clipboard

sqlc.embed handle CTE

Open alexandre-durand opened this issue 1 year ago • 2 comments

What do you want to change?

sqlc.embed does not recognize type from CTE (see repo link)

I have 2 examples:

  • one that works correctly :
WITH filtered_customers AS (
    SELECT c.*
    FROM customers AS  c
    WHERE c.deleted_at IS NULL
    AND (array_upper(@customer_ids::uuid[], 1) IS NULL OR c.id = ANY(@customer_ids))
    AND sqlc.narg('is_active')::bool IS NULL OR is_active = sqlc.narg('is_active')
), customer_managers_agg AS (
    SELECT cm.customer_id, array_agg(cm.user_id)::uuid[] AS managers
    FROM customers_managers AS cm
    INNER JOIN filtered_customers AS c ON c.id = cm.customer_id
    GROUP BY cm.customer_id
) SELECT sqlc.embed(c), cm.managers
FROM filtered_customers AS c
LEFT JOIN customer_managers_agg AS cm ON c.id = cm.customer_id
WHERE (array_upper(@manager_ids::uuid[], 1) IS NULL OR cm.managers && @manager_ids);

it generates:

type ListCustomersRow struct {
	Customer Customer
	Managers []uuid.UUID
}
  • one that fails:
-- name: CreateCustomer :one
WITH inserted_customer AS (
    INSERT INTO customers (
        name,
        team_id
    ) VALUES (
        @name,
        @team_id
    )
    RETURNING *
), inserted_managers AS (
    INSERT INTO customers_managers (customer_id, user_id)
    SELECT c.id AS customer_id, unnest(@manager_ids::uuid[]) AS user_id
    FROM inserted_customer AS c
)
SELECT sqlc.embed(c), @manager_ids::uuid[] AS managers
FROM inserted_customer AS c;

it generates the following error: unable to resolve table with "sqlc.embed(c)": relation "c" does not exist

What database engines need to be changed?

No response

What programming language backends need to be changed?

No response

alexandre-durand avatar Jan 12 '24 10:01 alexandre-durand

This would be very nice if supported.

dbarrosop avatar Nov 11 '24 08:11 dbarrosop

Would love to see this :)

zyriab avatar Apr 02 '25 20:04 zyriab