Skip to content

fix(gosqlx): ExtractColumns reports SELECT aliases referenced in ORDER BY/HAVING as columns #849

Closed

Description

@ajitpratap0

Summary

gosqlx.ExtractColumns and gosqlx.ExtractColumnsQualified report a SELECT-list alias as a column whenever the alias is referenced in ORDER BY or HAVING. The alias is an output name, not a column of any table.

Users see this in the MCP extract_metadata / analyze_sql tools and in the ChatGPT widget. In a live ChatGPT test, ORDER BY orders listed orders under Columns.

Reproduction (main @ f0ebf86)

tree, _ := gosqlx.Parse(sql)
gosqlx.ExtractColumns(tree)
gosqlx.ExtractColumnsQualified(tree)
SQL ExtractColumns Expected
SELECT u.id, COUNT(o.id) AS orders FROM users u LEFT JOIN orders o ON o.user_id = u.id GROUP BY u.id ORDER BY orders DESC [id orders user_id] [id user_id]
SELECT COUNT(*) AS total FROM t ORDER BY total [total] []
SELECT price * qty AS amount FROM items HAVING amount > 10 [amount price qty] [price qty]
SELECT COUNT(*) AS total FROM t (alias not referenced) [] [] ✅

The qualified variant has the same problem. For the first query it returns orders unqualified next to o.id o.user_id u.id.

Expected behaviour

An unqualified identifier in ORDER BY (and HAVING, which MySQL and others allow to use aliases) that matches a SELECT-list alias in the same query block should resolve to that alias and be left out of the column list.

Keep reporting the identifier as a column when:

  • it is qualified (t.total);
  • no alias in the same SELECT has that name.

Aliases from outer or inner query blocks (subqueries, CTEs) should not suppress columns in another block.

Notes

  • This lives in pkg/gosqlx/extract.go (column collector), not in the parser.
  • Add table-driven cases to pkg/gosqlx/extract_test.go, including a negative case where a real column shares a name with an alias defined in a subquery.
  • Found while testing the GoSQLX ChatGPT app (feat: GoSQLX Claude Code plugin and ChatGPT app #823).

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions