Skip to content

feat(query)!: 0.7.0 — single join form with required alias, getAlias(), typed cursors - #14180

Merged
abnegate merged 7 commits into
mainfrom
feat-query-070
Oct 7, 2026
Merged

abnegate merged 7 commits into
mainfrom
feat-query-070

Conversation

@abnegate

@abnegate abnegate commented Oct 7, 2026 •

Copy link
Copy Markdown
Member

What

utopia-php/query 0.7.0: one join form with a required alias, an alias property, typed cursors, a validated ON list, and the compile*Expr → compile*Expression hook renames. packages/audit and packages/usage accept utopia-php/query ^0.6 || ^0.7 in the same PR. bin/monorepo check resolves packages against the registry, so a bare ^0.7 cannot resolve until 0.7.0 is tagged. Linked test runs still pick the 0.7 line from this checkout. Both packages work on either line.

Query::join(string $collection, string $alias, array $on): static        // also leftJoin, rightJoin, fullOuterJoin
Query::crossJoin(string $collection, string $alias): static              // also naturalJoin
Query::on(string $left, string $right, string $operator = '='): static   // unchanged
$query->getAlias(): string                                               // joins and aggregates; replaces getJoinAlias()
Query::cursorAfter(array|object $value): static                          // also cursorBefore, and Builder\Feature\Selects
new Query(Method|string $method, string $attribute = '', array $values = [], string $alias = '')

Why

  • BUG-05. join($table, [$on], 'alias') matched none of the three join overloads, so the alias was dropped without an error. The ON list also accepted any query, so limit(), select() or an ordering inside it was only rejected, or ignored, at compile time. Both are now impossible: there is a single join form, and the ON list is checked when the join is built.
  • DEC-42/43. Keeping the alias in values[0] or values[3], depending on the overload, made every reader guess the position. The alias is now a property, serialised as "alias", and aggregates use the same property.
  • DEC-44, as the user answered it. Cursors are rows: arrays in the audit and usage ClickHouse adapters, documents in utopia-php/database. The builders read the row's _cursor column, which is the column they page on.
  • m12. These were the last abbreviated hook names on the builder surface. 0.7.0 already breaks the API, so the rename ships in the same release.

Breaking

  • The column form join($t, $left, $right, $op, $alias), the alias-less form and the alias-last form are removed. An empty alias throws ValidationException.
  • Each ON member must satisfy the new Method::isJoinCondition(): on(), comparisons, between, null checks, contains/containsAny/notContains, the startsWith/endsWith family, or and/or of those, at any depth. This is the same set the builders compile, and they now use the same method. Anything else throws ValidationException (Unsupported join ON condition: <method>), including search(), regex(), spatial, JSON and JSON strings.
  • getJoinAlias() is removed. An aggregate's alias is no longer in values[0].
  • cursorAfter()/cursorBefore() take array|object. The builders bind the row's _cursor value and throw if the row has none. A scalar cursor parsed from JSON still binds as it is.
  • Protected hooks are renamed: compileSearchExpr, compileJsonContainsExpr, compileJsonOverlapsExpr, compileJsonPathExpr and compileVectorOrderExpr become compile*Expression.
  • Serialised 0.6 queries still parse. parseQuery() reads "alias", falls back to values[0] (aggregates, cross/natural joins and alias-first joins) and to values[3] (column-form joins, which become a single on()), and applies the same validation as the factories.
  • The MongoDB builder reads the single form: one on() equality per $lookup, under the join's alias. A filtered ON list throws UnsupportedException instead of building a broken stage.
  • The fluent builder API (->join($table, $left, $right, $operator, $alias = ''), ->crossJoin(), …) is unchanged, and so is its SQL. Builders validate and quote aliases exactly as before.

The CHANGELOG has the full entry and a 0.6 → 0.7 upgrade table. The README documents join queries, aliases and cursor rows.

Tests

  • BUG-05 (fail-first). tests/API/JoinTest.php testOnListRejectsMemberThatIsNotACondition, with 19 non-condition members, at top level and nested in or(). Run against main 3a08617, the limit, select and orderAsc cases fail with "Failed asserting that exception of type ValidationException is thrown". The [on], 'alias' order compiles JOIN \orders` ON …with noAS `ord``. Both pass on this branch.
  • Joins. Every join factory: method, collection, alias and ON list, plus a required alias, a required condition and conditions that are not queries. Accepted condition types. Round trips through toArray/parseQuery/parse for each factory. Legacy values[0] (cross/natural, alias-first, aggregates) and values[3] (column form). The "alias" key winning over a legacy position. Parse rejections.
  • Cursors. Query::cursorAfter/cursorBefore with an array and with an object. A scalar is a TypeError. New tests/Builder/CursorTest.php covers array, ArrayAccess and plain-object rows on MySQL and PostgreSQL, a missing _cursor, and a parsed scalar.
  • MongoDB. A join query looks up under its alias. A filtered ON list is unsupported.
  • Unchanged. The existing alias and identifier-quoting tests (testJoinAlias*, testCrossJoinAlias*, testNaturalJoinWithAlias, testSelfJoinWithAlias, testJoinWhereWithAlias*, JoinTenancy-style hook tests) keep their assertions. The only test edits are the new call form and cursor rows.
  • Local, one file at a time. Every packages/query unit file except the performance group, and the audit and usage unit files, all pass. PHPStan is clean with the package config (level max, src and tests; the only errors are the pre-existing ones in the MongoDB\* classes of the E2E client, whose vendor package is missing locally). A full root PHPStan run is clean.
  • CI. Packages / query (check and test), plus audit and usage linked against this checkout. abuse does not depend on utopia-php/query, so it is not in the matrix.

Release: bin/monorepo release query 0.7.0 after merge. utopia-php/database picks it up in its 8.0 train.

🤖 Generated with Claude Code

abnegate and others added 3 commits October 7, 2026 16:11
The protected dialect hooks were the last abbreviated method names on the
builder surface (DEC-52, m12). 0.7.0 already breaks the join and cursor API,
so the rename rides the same minor instead of costing another one later.

compileSearchExpr, compileJsonContainsExpr, compileJsonOverlapsExpr,
compileJsonPathExpr and compileVectorOrderExpr become compile*Expression.
Subclasses must rename their overrides: an override of one of the abstract
SQL hooks fails to load until renamed, and an override of
compileVectorOrderExpression is otherwise no longer called. utopia-php/database
overrides the first three and renames them with its query 0.7 bump.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Joins had three overloads (column form, alias-first and an alias-less ON
list) whose meaning depended on argument types. Passing the ON list first and
the alias last matched none of them cleanly, so the alias was silently dropped,
and the ON list accepted any query, so limit(), select() or an ordering inside
it was only rejected, or ignored, when the query was compiled (BUG-05). The
database layer papered over missing aliases with generated ones (j0, j1, ...)
and table-name fallbacks.

Every join is now `join|leftJoin|rightJoin|fullOuterJoin($collection, $alias,
$on)` or `crossJoin|naturalJoin($collection, $alias)` (DEC-42). The alias is
required and the ON list is checked when the join is built: only on() and
filter conditions, at any depth of and/or, so a bad member fails where it is
written. Builders still validate and quote the alias as an identifier exactly
as before; the fluent builder API keeps its optional alias.

The alias moves into a property read by getAlias(), which replaces
getJoinAlias() and also serves aggregates instead of values[0] (DEC-43).
toArray() writes it as "alias"; parseQuery() still reads 0.6 payloads
(values[0] for aggregates, cross/natural and alias-first joins, values[3] for
column-form joins) so stored or cached queries keep parsing, and routes joins
through the same validation as the factories.

cursorAfter()/cursorBefore() take array|object (DEC-44 as answered by the
user): the audit and usage ClickHouse adapters page with array rows, the
database with documents. The builders read the row's _cursor column, the one
they page on, instead of binding whatever was passed.

The MongoDB builder now reads the single-form join (one on() equality per
$lookup, under the join's alias) and rejects filtered ON lists instead of
building a broken stage.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The monorepo resolves audit and usage against the query checkout, so their
0.6.* constraint stops resolving once packages/query is 0.7.0 (M5). Their
array and object cursors stay valid under the array|object typing, so no
call site changes.

audit's Query override of the constructor dropped anything past $values;
it now passes the alias on, so aliased aggregates built through the audit
class keep their alias. abuse does not depend on utopia-php/query and is
untouched.

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

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

Copy link
Copy Markdown

Review complete. 🟡 3 medium

💬 Inline comments (2)

  • 🟡 Cursor docs recommend forms the builder rejects — README.md:175
  • 🟡 AST join import drops multi-condition ON clauses — Builder.php:2616
📍 Findings outside the diff (1) — 🟡 1 medium — defects on lines GitHub can't attach comments to

🟡 Medium — MongoDB $lookup accepts empty on() columns · MongoDB.php:1322–1337 · unchanged line

// packages/query/src/Builder/MongoDB.php
1322	        /** @var array{0?: string, 1?: string, 2?: string} $columns */
1323	        $columns = $conditions[0]->getValues();
1324	        $leftCol = $columns[0] ?? '';
1325	        $operator = $columns[1] ?? '=';
1326	        $rightCol = $columns[2] ?? '';
1327	        $alias = $joinQuery->getAlias() !== '' ? $joinQuery->getAlias() : $table;
1328	
1329	        if ($operator !== '=') {
1330	            throw new UnsupportedException(
1331	                'MongoDB $lookup in localField/foreignField form only supports equality joins. '
1332	                . "Got operator '{$operator}'. Use a pipeline-form \$lookup via a raw stage for non-equality joins."
1333	            );

buildJoinStages defaults missing on() columns to empty strings and emits them into the $lookup stage as localField: '' / foreignField: '' (packages/query/src/Builder/MongoDB.php:1322-1337). The SQL builder throws ValidationException('Join ON requires left and right columns') for the same input (packages/query/src/Builder.php:1538-1540), but nothing on the Query side rejects an on() with empty columns, so Query::on('', 'b') — or untrusted input parsed via parseQuery with empty on values — reaches the MongoDB path. Impact: a malformed $lookup pipeline is sent to the server instead of failing fast with the validation the SQL dialect applies.

🧹 Nitpicks (3) — 🟢 3 low
  • 🟢 Alias-less builder joins fail parse round-trip (Query.php:1407) — createJoin hard-requires a non-empty alias (packages/query/src/Query.php:1407-1409), but the builder traits still default $alias = '' and construct the join via new Query(...) directly, bypassing that check (packages/query/src/Builder/Trait/Joins.php:14-34).
  • 🟢 Right-join round-trip test lost ON assertions (ParseTest.php:421) — The rewrite of testRoundTripRightJoin reduced it to asserting only Method::RightJoin (packages/query/tests/API/ParseTest.php:421-427), dropping the sibling tests' assertions on the attribute, alias and parsed ON shape — testRoundTripLeftJoin asserts getAttribute() and getJoinOnQueries()[0]->getValues() (lines 416-418), and testRoundTripJoinWithSpecialOperator asserts the ON values (line 434).
  • 🟢 Audit changelog wrongly says cursors unchanged (CHANGELOG.md:9) — The changelog states "Array and object cursors are unchanged" after bumping utopia-php/query from 0.6.* to ^0.7 (packages/audit/CHANGELOG.md:9-11), but query 0.7 narrows cursorAfter()/cursorBefore() from mixed to array|object and its own migration table lists Query::cursorAfter('id') as a breaking change requiring migration (packages/query/CHANGELOG.md:55).

The upgrade adopts query 0.7's breaking API changes: joins now carry an explicit alias and ON conditions as dedicated child queries, aggregate aliases moved from values[0] to the constructor's fourth argument, and cursorAfter()/cursorBefore() narrow from mixed to array|object with a new resolveCursorValue() path expecting a _cursor key.

Files Change
packages/query/src (Builder.php, SQL.php, dialects, Trait/*, Query.php) Refactor join compilation to alias+ON-query shape, rename compile*Expression hooks, add cursor row resolution; legacy 0.6 serialized joins still parse
packages/query/README.md, packages/query/CHANGELOG.md Document the 0.7 upgrade surface (joins, aggregates, cursors)
packages/audit, packages/usage Bump utopia-php/query to ^0.7, add the $alias constructor pass-through, changelog entries
packages/query/tests Rewrite join/parse/selection/cursor/dialect test suites for the new API and add a correctness regression suite

Reviewed commit: 132812c

@ghost

ghost commented Oct 7, 2026 •

Copy link
Copy Markdown

🟢 Tier S · Ready to merge

The previous OR-conversion defect is fixed, and the incremental changes introduce no findings requiring changes.

Introduces the query 0.7 API with required join aliases, a single join representation, alias properties, row-typed cursors, legacy parsing support, and renamed compilation hooks. SQL and MongoDB builders and their tests adopt these contracts, while audit and usage allow query ^0.6 or ^0.7. AST join conversion now preserves both OR operands, including nested AND conditions.

Latest changes: The newest commits recursively convert OR operands with the join-aware converter and add a regression test covering column comparisons alongside nested AND predicates.

Verdict New comments Fixed Still open
✅ Approved 0 1 0
📂 Walkthrough · 14
File Change
packages/audit/{CHANGELOG.md,composer.json,src/Query.php} Allow query ^0.6 or ^0.7 and forward the optional constructor alias.
packages/query/{CHANGELOG.md,README.md} Document breaking APIs, migration examples, aliases, join conditions, and cursor rows.
packages/query/src/{Query.php,Method.php} Add alias storage, single-form joins, typed cursors, legacy parsing, and recursive ON validation.
packages/query/src/Builder.php Adopt join and cursor contracts, rename the vector hook, and preserve AND/OR predicates during AST join conversion.
packages/query/src/Builder/MongoDB.php Read aliases and restrict lookups to a single equality with nonempty join columns.
packages/query/src/Builder/{SQL,MySQL,PostgreSQL,SQLite}.php Rename search, JSON, and vector compilation hooks consistently.
packages/query/src/Builder/{Feature/Selects.php,Trait/Selects.php} Restrict fluent cursor inputs to arrays or objects.
packages/query/src/Builder/Trait/{CrossJoins,FullOuterJoins,Joins}.php Retain fluent signatures while constructing the new query layout.
packages/query/tests/API/{AggregationTest,HelperTest,JoinTest,ParseTest,SelectionTest}.php Cover aliases, legacy parsing, cursor types, and ON-condition validation.
packages/query/tests/AST/BuilderAstTest.php Cover unsupported joins and preservation of conjunctive and disjunctive ON predicates.
packages/query/tests/Builder/{ClickHouseTest,CursorTest,MongoDBTest,MySQLTest,PostgreSQLTest}.php Migrate join and cursor calls and test cursor extraction and MongoDB lookup restrictions.
packages/query/tests/{QueryTest.php,Regression/CorrectnessRegressionTest.php} Adapt existing coverage to the single join form.
packages/usage/{CHANGELOG.md,composer.json} Allow query ^0.6 or ^0.7 and document compatibility.
packages/query/src/Query.php Introduce alias storage, typed cursors, single-form joins, recursive ON validation, and legacy parsing.
✅ Fixed since the last review · 1
  • Preserve both operands when converting OR join conditions · packages/query/src/Builder.php:2622

Reviewed the commits since af982d6 · 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 B · 1 blocking finding to address. Summary

Comment thread packages/query/src/Query.php Resolved

@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 bumps packages/query to utopia-php/query 0.7 with the refactored join/alias API and cursor typing, cascading the bump to packages/audit and packages/usage, and updates the test suites accordingly.

Key findings

Comment thread packages/query/README.md Resolved
Comment thread packages/query/src/Builder.php Resolved
abnegate and others added 2 commits October 7, 2026 16:19
The factories accepted search, regex, spatial, JSON and containsAll members
in an ON list, which every builder then rejected at compile time, so the
early check promised joins that could never build. Method::isJoinCondition()
is now the one set both use: on(), the comparisons, between, null checks,
contains/containsAny/notContains, the startsWith/endsWith family, and and/or
of those. It is the set the builders and utopia-php/database's join
validator already allow. Errors use the builders' existing message.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
bin/monorepo check installs a package registry-resolved, and 0.7.0 is not on
Packagist until this PR merges and is released, so a bare ^0.7 cannot
resolve. audit and usage run on both lines: they page with array and object
cursors and use none of the join or alias API. Linked test runs still pick
the newest line (0.7.999), so CI tests them against this checkout.

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

github-actions Bot commented Oct 7, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → feat-query-070 (after).

Metric Before After Change
🚀 Requests/sec 198.52 202.14 ⚪ +1.8%
⏱️ Latency P50 85.08 ms 86.53 ms ⚪ +1.7%
⏱️ Latency P95 213.64 ms 199.12 ms 🟢 -6.8%
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 86.53 199.12 12,540 202.14 -14.52
Account 170.18 312.7 660 11.26 -10.31
TablesDB 84.53 158.58 6,820 112.21 +10.54
Storage 77.25 169.73 3,300 56.01 -17.58
Functions 118.98 235.42 1,760 30.57 -40.64

Top API waits (after)

API request Max wait (ms)
account.prefs.update 495.71
functions.variables.update 492.8
account.name.update 478.02
functions.delete 460.45
functions.variables.create 434.27

@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

…okup columns

applyAstJoins turned a parsed join condition into one on() only when it was
a single comparison, so `ON a.x = b.x AND a.y = b.y` became on(..., 'AND')
and failed to compile, and any other shape left the ON list empty. It now
walks the AND chain: column-to-column comparisons become on(), other leaves
become the filter queries the WHERE import already produces, and a leaf that
is not a join condition throws instead of vanishing.

The MongoDB $lookup took an on() with an empty column as an empty
localField/foreignField; it now throws the same "left and right columns"
error the SQL builders do.

The README and the upgrade table showed cursor rows the bundled builders
reject; they now show the `_cursor` row and say custom compilers read their
own columns.

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

@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 B · 1 blocking finding to address. Summary

Comment thread packages/query/src/Builder.php Resolved
… SQL

The join-condition import handed OR to the WHERE converter, which drops
operands it cannot represent, so `a.id = o.a_id OR o.status = 'paid'` lost
the column comparison and joined different rows. OR operands now go through
the join-aware converter, so a column comparison stays an on() and an AND
group stays an and(); anything unrepresentable still throws.

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

@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

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