Skip to content

fix(database): prevent incorrect identifier quoting inside function field expressions - #2331

Open
abu-tahir-0 wants to merge 1 commit into
tempestphp:3.xfrom
abu-tahir-0:fix/field-statement-function-quoting
Open

abu-tahir-0 wants to merge 1 commit into
tempestphp:3.xfrom
abu-tahir-0:fix/field-statement-function-quoting

Conversation

@abu-tahir-0

Copy link
Copy Markdown

Problem

Fixes #2329.

When using SQL functions containing qualified column names in select() (e.g. COUNT(item.id) AS count or AVG(order.total)), FieldStatement::compile() generates invalid SQL such as COUNT(item.id)AScount``. This syntax error causes query execution to fail on MySQL and PostgreSQL.

Root Cause

In FieldStatement::compile(), $field is split on . before checking for function calls:

$field = arr(explode('.', $field))
    ->map(...)
    ->map(function (string $part) use ($dialect) {
        if (str_contains($part, '(')) {
            return $part;
        }
        ...
        return $dialect->quoteIdentifier($part);
    })

When $field is COUNT(item.id), exploding on . produces ['COUNT(item', 'id)']. Because only the first part contains (, the second part id) is incorrectly quoted by quoteIdentifier(), resulting in COUNT(item.id)`.

Solution

Check if (! str_contains($field, '(')) before exploding on .. When a field expression contains parentheses (indicating an aggregate function or expression), skip identifier quoting on the expression itself while preserving alias quoting (e.g. AS \count`orAS "count"`).

Testing

  • Added regression tests in FieldStatementTest covering COUNT(item.id) AS count across SQLite, MySQL, and PostgreSQL dialects.
  • Verified all 212 tests in packages/database/tests pass.
  • PHPStan analysis clean.

Impact

Allows queries with aggregate functions or function calls referencing joined table columns to compile valid SQL without identifier quoting syntax errors.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

SQL quoting error when select includes count on joined table

1 participant