ReviewOS

stacks/bun-query-builder

A join cannot alias its table, so a self-join cannot be written

#1195
Closed glennmichael123 opened this 7 days ago ·
7 days ago

What happens

A join cannot alias its table, so a self-join cannot be written:

db.selectFrom('categories as c')
  .leftJoin('categories as parent', 'c.parent_category_id', '=', 'parent.id')
[query-builder] Invalid identifier in leftJoin(table): 'categories as parent'. Identifiers must start with a letter or underscore and contain only alphanumeric ...

selectFrom accepts table AS alias (it validates with assertSafeColumnRef), but join / innerJoin / leftJoin / rightJoin / crossJoin validate their table with validateIdentifier, which allows a bare name only (packages/bun-query-builder/src/client.ts, e.g. leftJoin(table2, ...) around L6197). Joining a table to itself needs a second name for it, so there is no non-raw way to express it.

Found in Stacks: core/commerce/src/products/categories/fetch.ts fetchStats (top parent categories) has failed with this since the identifier hardening (3827868).

Proposed fix

Accept table AS alias (case-insensitive as, both parts plain identifiers) as the table argument of every join, render it quoted as "table" AS "alias", and let the on columns reference the alias. Anything else keeps being rejected.

Sign in to comment on this issue.