Skip to content

feat(query): read a join without an alias under its collection - #14594

Merged
abnegate merged 2 commits into
mainfrom
fix/join-default-alias
Oct 16, 2026
Merged

abnegate merged 2 commits into
mainfrom
fix/join-default-alias

Conversation

@abnegate

Copy link
Copy Markdown
Member

What

A join given no alias is now read under the name of the collection it joins, instead of throwing Join alias is required. This covers the factories (join, leftJoin, rightJoin, fullOuterJoin, crossJoin, naturalJoin with '') and parse()/parseQuery() in every layout they accept: the alias property, the legacy alias-first and column forms, the nested ON form, and cross/natural joins. A join with neither a collection nor an alias still throws.

The factory signature from 0.7.0 is unchanged (join(string $collection, string $alias, array $on)); '' now means "use the collection".

Query::isAliasDefaulted() (new) tells consumers that a join is read under its collection's name, so they can say why that name can't be used when their own alias rules reject it. utopia-php/database uses it for its pattern, reserved-name, relationship-key and duplicate checks. None of that knowledge lives here.

How the defaulted state is represented

It is derived in the constructor as "this join's alias equals its collection". It is not a new serialised key:

  • toArray() still emits the alias, so a toArray()/parse() or toString()/parse() round trip re-derives the same flag. There is no new wire field that untrusted input could set out of step with the alias.
  • Appwrite's Joins hook swaps the public collection ID for the internal table with (clone $query)->setAttribute(...). That keeps both the alias and the flag, because neither is recomputed from the renamed collection. Rows stay keyed "<publicId>.<column>". Leaving the alias out of toArray() would instead have re-defaulted it to the internal table name on a later parse. testDefaultedAliasSurvivesRenamingTheCollection pins this.
  • An explicit alias equal to the collection reads exactly like a defaulted one, so it also counts as defaulted.

Builder joins (new Query(Method::Join, ...) with no alias, as Builder::join() creates) stay unaliased, so their generated SQL is unchanged (testBuilderJoinWithoutAliasStaysUnaliased).

Tests: fail before, pass after

New tests are in packages/query/tests/API/JoinTest.php. Each was run against the main src/Query.php and then against this branch:

Test main this PR
testConditionedJoinWithoutAliasIsReadUnderItsCollection (join, leftJoin, rightJoin, fullOuterJoin) 4 errors (Join alias is required) pass
testUnconditionedJoinWithoutAliasIsReadUnderItsCollection (crossJoin, naturalJoin) 2 errors pass
testParsedJoinWithoutAliasIsReadUnderItsCollection (nested ON, empty alias property, empty alias-first, column form, column form with empty alias, crossJoin, crossJoin with empty legacy alias, naturalJoin) 8 errors pass
testParsedJoinWithoutAliasRoundTrips (same 8 layouts, toArray() and toString() round trips) 8 errors pass
testDefaultedAliasSurvivesRenamingTheCollection error pass
testDefaultedJoinCompilesUnderItsCollection error pass
testConditionedJoinWithAliasIsNotDefaulted / testUnconditionedJoinWithAliasIsNotDefaulted / testParsedJoinWithAliasRoundTripsAsNotDefaulted / testJoinAliasedAsItsCollectionCountsAsDefaulted / testQueriesOtherThanJoinsAreNeverDefaulted / testBuilderJoinWithoutAliasStaysUnaliased 12 errors (no isAliasDefaulted()) pass
testConditionedJoinWithoutAliasOrCollectionIsRejected / testUnconditionedJoinWithoutAliasOrCollectionIsRejected / testParseRejectsJoinWithoutAliasOrCollection pass (unchanged behaviour, pinned) pass

Before: 41 tests, 34 errors. After: the full bin/monorepo test query unit tier passes (5568 tests). bin/monorepo check query (Pint, PHPStan, Rector) passes.

Next, once this is released as query/0.7.2: a utopia-php/database PR bumps to ^0.7.2 and adds the validator rules and messages, plus e2e tests on every adapter.

🤖 Generated with Claude Code

An alias is only needed to tell two joins of one collection apart, so
requiring it on every join made the common single join of a table more
verbose than it needs to be. The factories and parse() now read a join given
an empty alias under the collection it joins, in every accepted layout (the
alias property, the legacy alias-first and column forms, the nested ON form,
cross and natural joins). The single typed factory signature from 0.7.0 stays,
so nothing silently drops an alias again; '' just means "use the collection".
Only a join with neither a collection nor an alias still throws.

Whether a join is read under its collection's name is exposed as
isAliasDefaulted() so consumers can explain why that name cannot be an alias
(their own naming rules live with them). It is derived in the constructor as
"the join's alias equals its collection" rather than serialised as a new key:

- toArray() keeps emitting the alias itself, so a round trip through
  toArray()/parse() re-derives the same flag without a new wire field that
  untrusted input could set out of step with the alias.
- Consumers that point a join at another table after parsing (Appwrite swaps
  the public collection ID for its internal table via clone + setAttribute())
  keep both the alias and the flag, since neither is recomputed from the
  renamed collection. Omitting the alias from toArray() instead would have
  re-defaulted it to the internal table name on a later parse.
- An explicit alias equal to the collection reads exactly like a defaulted
  one, so treating it as defaulted is accurate for any message built on it.

Builder joins (new Query(Method::Join, ...) with no alias) are left unaliased,
so generated SQL for them is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@luxor-code-review

luxor-code-review Bot commented Oct 16, 2026 •

Copy link
Copy Markdown

Review complete. 🟡 1 medium

📍 Findings outside the diff (1) — 🟡 1 medium — defects on lines GitHub can't attach comments to

🟡 Medium — Persist aliasDefaulted state through serialization · Query.php:454–472 · unchanged line

// packages/query/src/Query.php
454	    public function toArray(): array
455	    {
456	        $array = ['method' => $this->method->value];
457	
458	        if (! empty($this->attribute)) {
459	            $array['attribute'] = $this->attribute;
460	        }
461	
462	        if ($this->alias !== '') {
463	            $array['alias'] = $this->alias;
464	        }
465	

aliasDefaulted is never serialized: toArray() (packages/query/src/Query.php:454) emits only method, attribute, alias and values, so parseQuery() re-derives the flag from alias === $attribute in the constructor (packages/query/src/Query.php:53). After a defaulted join's collection is renamed via setAttribute() and the query is then serialized and parsed back, the flag flips to false even though the join is still read under its defaulted alias — contradicting the README (line 183) and CHANGELOG guarantee that the flag survives setAttribute(), toArray() and parse(). The same missing state means a builder-built join with an intentionally empty alias (new Query(Method::Join, 'orders', [$on])) mutates on a round trip: toArray() omits the alias (packages/query/src/Query.php:462), and reparse normalizes it to orders with the flag true, changing compiled SQL from JOIN orders to JOIN orders AS orders. Consumers keying on the flag after a round trip (cursors, queued queries) misclassify the alias.


The change fixes a bug where a join without an explicit alias lost its identity when the joined collection was renamed: the alias is now defaulted to the collection name and tracked via isAliasDefaulted(), with README, CHANGELOG, and join tests updated to document and cover the new behavior.

Files Change
packages/query/src/Query.php Adds derived aliasDefaulted state, alias defaulting on join construction, and validation guards around join aliases.
packages/query/tests/API/JoinTest.php Adds join aliasing tests covering rename-survival and defaulted-alias parsing.
packages/query/README.md Documents the alias-defaulting behavior and its guarantees.
packages/query/CHANGELOG.md Records the alias-defaulting fix.

One medium-severity issue was found: the aliasDefaulted flag is not persisted through toArray()/parseQuery(), so a round trip can flip the flag for renamed or unaliased joins.

Reviewed commit: 35c311d

@ghost

ghost commented Oct 16, 2026 •

Copy link
Copy Markdown

🟢 Tier S · Ready to merge

The latest changes align the documented and tested serialization behavior, with no remaining actionable issues found.

This PR lets joins with an empty alias be read under their collection name across the factory and parsing forms, and adds isAliasDefaulted() to expose that state. It also covers compilation, serialization, collection renaming, and builder-constructed joins, with corresponding documentation and changelog updates.

Latest changes: The latest commits clarify that a renamed join preserves its alias when serialized but is parsed as explicitly aliased, and add tests for that behavior and for parsing an unaliased builder join.

Verdict New comments Fixed Still open
✅ Approved 0 0 0
📂 Walkthrough · 4
File Change
packages/query/CHANGELOG.md Documents join alias defaulting and how a renamed join's serialized alias is interpreted.
packages/query/README.md Clarifies defaulted-alias derivation and the renamed-join serialization behavior.
packages/query/src/Query.php Defaults empty join aliases, tracks defaulted state, parses supported join forms, and exposes isAliasDefaulted().
packages/query/tests/API/JoinTest.php Covers defaulted joins, supported parse and round-trip layouts, compilation, renamed joins, and builder joins.

Reviewed the commits since 35c311d · Details · Comment @hansi-codes review to re-run, or mention @hansi-codes with a question.

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Tier A · See the inline comments. Summary

Comment thread packages/query/src/Query.php Resolved
@github-actions

Copy link
Copy Markdown

Security rules

No new WARNING or ERROR findings from security rules.

19 existing findings tracked in .semgrep/baseline.json
  • php.appwrite.guest-write-without-abuse-limit (12)
  • php.appwrite.secret-compare-timing (5)
  • php.appwrite.weak-secret-env-default (2)

Posted by Checks / Rules. Re-runs update this comment in place. Rule details and baseline: .semgrep/README.md.

@github-actions

github-actions Bot commented Oct 16, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → fix/join-default-alias (after).

Metric Before After Change
🚀 Requests/sec 208.38 210.72 ⚪ +1.1%
⏱️ Latency P50 80.92 ms 81.68 ms ⚪ +0.9%
⏱️ Latency P95 196.75 ms 191.46 ms ⚪ -2.7%
Per-scenario breakdown & investigation details

Metrics below reflect the current branch (after). Δ P95 compares against the base.

Scenario P50 (ms) P95 (ms) Requests RPS Δ P95 (ms)
API total 81.68 191.46 13,452 210.72 -5.29
Account 158.3 295.25 708 11.76 -3.25
TablesDB 78.15 144.07 7,316 117.78 -1.04
Storage 77.71 171.75 3,540 58.22 -17.32
Functions 118.79 231.35 1,888 31.84 -21.03

Top API waits (after)

API request Max wait (ms)
account.name.update 469.68
functions.create 413.14
tablesdb.rows.create 409.59
functions.variables.update 379.62
account.prefs.update 377.32

The defaulted flag is derived from the serialized form, so a join serialized
after setAttribute() renamed its collection is parsed as an explicit alias.
That is the intended trade-off: the alias itself is kept (rows stay keyed by
the public name), and the flag only feeds consumers' wording, which they read
from the in-memory query. The README and changelog claimed the flag survived
that combination; say what actually happens and pin it, along with the
round trip of an unaliased builder join.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@abnegate

Copy link
Copy Markdown
Member Author

@tenki-reviewer re the serialization finding: same answer as the inline thread. This is intended, and the docs overstated it. Fixed in 8f95a91: the README and changelog now say what happens.

The flag is derived from the serialized form (alias equals collection) on purpose. A join serialized after setAttribute() renamed its collection therefore keeps its alias, so rows stay keyed by the public name and nothing leaks the internal table. parse() then reads that alias as an explicit one. The flag only feeds a consumer's error wording, and consumers read it from the in-memory query: utopia-php/database validates after its query hooks rewrite the collection, on the cloned object, where the flag is intact. Carrying the flag on the wire would add a field that untrusted input could set out of step with the alias. Dropping the alias from toArray() would re-default it to the internal table name on the next parse, which is the leak this design avoids.

testRenamedJoinSerializesItsAliasExplicitly pins this behaviour. testBuilderJoinWithoutAliasParsesUnderItsCollection pins the unaliased builder join round trip: parsing a join with no alias defaulting it is the change itself, and before this PR that round trip threw.

@luxor-code-review

luxor-code-review Bot commented Oct 16, 2026 •

Copy link
Copy Markdown

Review complete. 🟡 1 medium

💬 Inline comments (1)

  • 🟡 Defaulted alias can shadow the base table or duplicate another join alias — Query.php:1464

The change relaxes the join DSL so that an empty alias no longer throws: joins without an explicit alias now default to their collection name, and a aliasDefaulted marker tracks which aliases were defaulted so serialization round trips stay stable. Tests cover the new defaulting behavior across parse forms. | Files | Change | |---|---| | packages/query/src/Query.php | Defaults empty join aliases to the collection name and tracks the defaulted flag through toArray()/parse(). | | packages/query/tests/API/JoinTest.php | Adds tests for empty-alias defaulting and round-trip fidelity. | | packages/query/README.md | Documents the new alias-defaulting behavior. | | packages/query/CHANGELOG.md | Notes the feature release entry. |

Reviewed commit: 8f95a91

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Tier S · Looks good to merge. Summary

@luxor-code-review luxor-code-review Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This PR lets Query::join() default an omitted alias to the collection name while preserving a defaulted-alias flag across toArray()/parse() round trips, with matching tests and docs.

Key findings

  • 🟡 Defaulted alias can shadow the base table or duplicate another join alias — Query.php:1464

Comment thread packages/query/src/Query.php Resolved
@abnegate
abnegate merged commit 60b8aeb into main Oct 16, 2026
238 checks passed
@ChiragAgg5k ChiragAgg5k mentioned this pull request Oct 21, 2026
6 tasks
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.

1 participant