houqp / sqlvet

Go fearless SQL. Sqlvet performs static analysis on raw SQL queries in your Go code base.
MIT License
493 stars 25 forks source link

table not available error for query with LEFT JOIN LATERAL #26

Closed valichek closed 8 months ago

valichek commented 1 year ago

sqlvet fails with:

ERROR: table `w` not available for query

on query similar to:

SELECT d.id, coalesce(w.w_count,0) as w_count FROM my_table AS d
LEFT JOIN LATERAL ( 
    SELECT count(*) as w_count FROM my_another_table WHERE d.id = ext_id AND deleted_at IS NULL
) w ON true
WHERE d.deleted_at IS NULL;
samiam2013 commented 1 year ago

Can you alias with AS w? or is that disallowed by postgres/does it fail in the same way?

valichek commented 1 year ago

Can you alias with AS w? or is that disallowed by postgres/does it fail in the same way?

Using AS w is valid option for postgres with same result, anyway it still fails with the same sqlvet error

SELECT d.id, coalesce(w.w_count,0) as w_count FROM my_table AS d
LEFT JOIN LATERAL ( 
    SELECT count(*) as w_count FROM my_another_table WHERE d.id = ext_id AND deleted_at IS NULL
) AS w ON true
WHERE d.deleted_at IS NULL;
houqp commented 1 year ago

I think the join clause parsing logic needs to be extended to handle table aliases so w can be registered as a table in ctx.schema on the fly: https://github.com/houqp/sqlvet/blob/4e66a9896fb9d1dc54c810a5e54d8119e507d44c/pkg/vet/vet.go#L196