Skip to content

Conversation

@fogelito
Copy link
Contributor

@fogelito fogelito commented Nov 20, 2025

Summary by CodeRabbit

  • New Features

    • Added multi-collection joins (inner/left/right) and a query context to drive cross-collection queries and permissions.
  • Refactor

    • Selection moved to per-field selects; query/adapter flows are now context-aware, with improved join, filter, vector/spatial ordering, and per-join scoping.
    • Validation rewritten to validate queries against the context-aware schema.
  • Tests

    • Expanded unit and end-to-end tests to cover joins, per-field selection semantics, relationship projections, and context-driven validation.

✏️ Tip: You can customize this high-level summary in your review settings.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
src/Database/Database.php (2)

4179-4203: Relationship population can be skipped when only system selects are present.

processRelationshipQueries() adds $id, and you later add $permissions. That makes empty($selects) false even when the caller passed no selects, so relationship population is skipped unless nested selections exist. This effectively disables default relationship resolution for collections with relationships.

Consider tracking explicit user selects before system additions (and use that in the guard), and apply the same logic in find().

🔧 Suggested fix (apply similarly in find())
-        $selects = Query::getSelectQueries($queries);
+        $selects = Query::getSelectQueries($queries);
+        $hasExplicitSelects = !empty($selects);
@@
-        if (!$this->inBatchRelationshipPopulation && $this->resolveRelationships && !empty($relationships) && (empty($selects) || !empty($nestedSelections))) {
+        if (
+            !$this->inBatchRelationshipPopulation
+            && $this->resolveRelationships
+            && !empty($relationships)
+            && (!$hasExplicitSelects || !empty($nestedSelections))
+        ) {

Also applies to: 4266-4271


4865-4889: Select aliases (as) aren’t honored in the post-filtering path.

applySelectFiltersToDocuments() keeps attributes by getAttribute() only. If a select uses as, the alias field is dropped and the original key is retained, which diverges from normal select behavior (especially in relationship batch population).

🔧 Suggested fix
-        $attributesToKeep = [];
+        $attributesToKeep = [];
+        $aliasMap = [];
 
-        foreach ($selectQueries as $selectQuery) {
-            $attributesToKeep[$selectQuery->getAttribute()] = true;
-        }
+        foreach ($selectQueries as $selectQuery) {
+            $attr = $selectQuery->getAttribute();
+            $as = $selectQuery->getAs() ?? $attr;
+            $attributesToKeep[$as] = true;
+            $aliasMap[$attr] = $as;
+        }
@@
-        foreach ($documents as $doc) {
+        foreach ($documents as $doc) {
+            foreach ($aliasMap as $attr => $as) {
+                if ($as !== $attr && $doc->offsetExists($attr)) {
+                    $doc->setAttribute($as, $doc->getAttribute($attr));
+                    $doc->removeAttribute($attr);
+                }
+            }
             $allKeys = \array_keys($doc->getArrayCopy());
             foreach ($allKeys as $attrKey) {
src/Database/Adapter/Mongo.php (1)

2042-2073: Ensure consistent stdClass-to-array conversion across cursor batches.

The first batch uses convertStdClassToArray(), but getMore batches don’t, producing mixed shapes across the result set. Apply the same conversion for all batches.

🐛 Proposed fix
-                    $doc = new Document($record);
+                    $doc = new Document($this->convertStdClassToArray($record));
♻️ Duplicate comments (7)
src/Database/Validator/Queries/V2.php (1)

187-191: Verify getRightAlias() return value for non-relation queries in join scope.

This check runs for all queries within join scope, but non-relation queries (filters, orders) may not have a meaningful rightAlias. If getRightAlias() returns an empty string for such queries, in_array('', $this->joinsAliasOrder) will fail and incorrectly reject valid queries.

The previous review suggested narrowing this check to TYPE_RELATION_EQUAL queries only. If that wasn't applied, consider:

                 if ($scope === 'joins') {
-                    if (!in_array($query->getAlias(), $this->joinsAliasOrder) || !in_array($query->getRightAlias(), $this->joinsAliasOrder)) {
+                    // Only validate alias references for relation queries that actually use rightAlias
+                    if (
+                        $query->getMethod() === Query::TYPE_RELATION_EQUAL &&
+                        (!in_array($query->getAlias(), $this->joinsAliasOrder, true) || !in_array($query->getRightAlias(), $this->joinsAliasOrder, true))
+                    ) {
                         throw new \Exception('Invalid query: '.\ucfirst($query->getMethod()).' alias reference in join has not been defined.');
                     }
                 }
#!/bin/bash
# Check what getRightAlias returns for non-relation queries
ast-grep --pattern $'class Query {
  $$$
  getRightAlias($$$) {
    $$$
  }
  $$$
}'
src/Database/Database.php (1)

8777-8782: Drop unused $idAdded from processRelationshipQueries().

$idAdded is never used; PHPMD already flags it. This can be removed by only capturing the updated $queries from QueryContext::addSelect(...). Based on learnings, this should stay relationship-only and avoid the unused local.

🔧 Suggested fix
-        if (!empty($relationships)) {
-            [$queries, $idAdded] = QueryContext::addSelect($queries, Query::select('$id', system: true));
-        }
+        if (!empty($relationships)) {
+            [$queries] = QueryContext::addSelect($queries, Query::select('$id', system: true));
+        }
src/Database/Adapter/Mongo.php (1)

1973-1980: Still missing guard for TYPE_ORDER_RANDOM before getOrderDirection().

This matches the prior review note; if random order can reach this adapter, it will still throw.

src/Database/Adapter/SQL.php (4)

374-378: Quote _uid consistently in getDocument() WHERE.
The column is currently unquoted while the alias is quoted; keep identifier quoting consistent to avoid edge cases with reserved words or quoting changes.

♻️ Suggested fix
-            WHERE {$this->quote($alias)}._uid = :_uid 
+            WHERE {$this->quote($alias)}.{$this->quote('_uid')} = :_uid 

2370-2405: Guard projection builder against non‑SELECT queries.
getAttributeProjection() is used with $queries in getDocument(). If the array is mixed, non‑SELECT queries can generate invalid projection SQL. Add a method check to skip non‑SELECT entries.

♻️ Suggested fix
         foreach ($selects as $select) {
+            if ($select->getMethod() !== Query::TYPE_SELECT) {
+                continue;
+            }
             if ($select->getAttribute() === '$collection') {
                 continue;
             }

3106-3111: Ensure skipAuth() uses the same key format as QueryContext::addSkipAuth().
Filtering the collection id before skipAuth() may prevent matches if the context stores raw ids.

Also applies to: 3268-3273


3132-3135: Quote alias/column in right‑join NULL permission clause.
The OR {$alias}._uid IS NULL branch mixes unquoted identifiers with quoted ones.

♻️ Suggested fix
-            if ($rightJoins) {
-                $permissionsCondition = "($permissionsCondition OR {$alias}._uid IS NULL)";
-            }
+            if ($rightJoins) {
+                $permissionsCondition = sprintf(
+                    '(%s OR %s.%s IS NULL)',
+                    $permissionsCondition,
+                    $this->quote($alias),
+                    $this->quote('_uid'),
+                );
+            }

Also applies to: 3294-3297

🧹 Nitpick comments (2)
src/Database/Validator/Queries/V2.php (2)

77-79: Minor typo in comment.

The comment has a grammatical error.

         /**
-         * Since $context includes Documents , clone if original data is changes.
+         * Since $context includes Documents, clone if original data is changed.
          */

659-681: Use Database::VAR_RELATIONSHIP constant instead of string literal.

Line 659 uses the string 'relationship' while line 547 and line 604 use Database::VAR_RELATIONSHIP. This inconsistency could cause subtle bugs if the constant value ever changes.

♻️ Suggested fix
-        if ($attribute['type'] === 'relationship') {
+        if ($attribute['type'] === Database::VAR_RELATIONSHIP) {

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/Database/Query.php (1)

1264-1280: Copy-paste bugs: fallback values use $limit instead of correct variables.

Lines 1270 and 1279 incorrectly fall back to $limit instead of $offset and $cursor respectively. While the null-coalescing operator makes these fallbacks rarely triggered (values should always exist for valid queries), the code is misleading and could cause subtle bugs if a malformed query slips through.

Proposed fix
                 case Query::TYPE_OFFSET:
                     // Keep the 1st offset encountered and ignore the rest
                     if ($offset !== null) {
                         break;
                     }

-                    $offset = $values[0] ?? $limit;
+                    $offset = $values[0] ?? null;
                     break;
                 case Query::TYPE_CURSOR_AFTER:
                 case Query::TYPE_CURSOR_BEFORE:
                     // Keep the 1st cursor encountered and ignore the rest
                     if ($cursor !== null) {
                         break;
                     }

-                    $cursor = $values[0] ?? $limit;
+                    $cursor = $values[0] ?? null;
                     $cursorDirection = $method === Query::TYPE_CURSOR_AFTER ? Database::CURSOR_AFTER : Database::CURSOR_BEFORE;
                     break;
🤖 Fix all issues with AI agents
In `@tests/unit/Validator/QueryTest.php`:
- Around line 268-275: Replace the unsafe use of reset() and the wrong
assertion: instead of $cursor = reset($queries) (which can be false), assign
$cursor = $queries[0] after asserting the array has two elements; and change the
incorrect assertNotEquals on $queries[1]->getMethod() to
assertEquals($queries[1]->getMethod(), Query::TYPE_CURSOR_AFTER) so the second
query is asserted to be the cursor-after type; keep references to
Query::getCursorQueries, $cursor, getMethod, Query::TYPE_CURSOR_BEFORE and
Query::TYPE_CURSOR_AFTER to locate the lines to change.
🧹 Nitpick comments (1)
src/Database/Query.php (1)

350-378: Use QueryException instead of generic \Exception for consistency.

The getCursorDirection() and getOrderDirection() methods throw \Exception, but the rest of the class uses QueryException for error handling. This inconsistency could make error handling more difficult for consumers.

Suggested fix
     public function getCursorDirection(): string
     {
         if ($this->method === self::TYPE_CURSOR_AFTER) {
             return Database::CURSOR_AFTER;
         }

         if ($this->method === self::TYPE_CURSOR_BEFORE) {
             return Database::CURSOR_BEFORE;
         }

-        throw new \Exception('Invalid method: Get cursor direction on "'.$this->method.'" Query');
+        throw new QueryException('Invalid method: Get cursor direction on "'.$this->method.'" Query');
     }

     public function getOrderDirection(): string
     {
         if ($this->method === self::TYPE_ORDER_ASC) {
             return Database::ORDER_ASC;
         }

         if ($this->method === self::TYPE_ORDER_DESC) {
             return Database::ORDER_DESC;
         }

         if ($this->method === self::TYPE_ORDER_RANDOM) {
             return Database::ORDER_RANDOM;
         }

-        throw new \Exception('Invalid method: Get order direction on "'.$this->method.'" Query');
+        throw new QueryException('Invalid method: Get order direction on "'.$this->method.'" Query');
     }

# Conflicts:
#	src/Database/Query.php
#	tests/unit/Validator/QueryTest.php
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
src/Database/Query.php (1)

1069-1080: Breaking change: getByType visibility reduced to protected.

Changing getByType from public to protected is a breaking API change. External consumers and tests that call this method directly will fail. The pipeline failures confirm this affects the test suite.

If this is intentional, consider:

  1. Providing public alternatives (which you've done with getCursorQueries, getSelectQueries, etc.)
  2. Documenting this breaking change in release notes

The test file needs to be updated to use the new public methods instead.

tests/unit/Validator/QueryTest.php (1)

258-324: Pipeline failure: Calling protected method Query::getByType().

Lines 266 and 288 call Query::getByType() which is now protected, causing the pipeline to fail. The test is meant to verify the behavior of filtering queries by type, but must use the public API.

Since this test specifically validates the clone vs reference behavior of getByType, you could:

  1. Remove the direct getByType calls and rely on the specialized public methods
  2. Keep one test using getCursorQueries to verify the same behavior
Proposed fix using public getCursorQueries method
     public function testQueryGetByType(): void
     {
         $queries = [
             Query::equal('key', ['value']),
             Query::cursorBefore(new Document([])),
             Query::cursorAfter(new Document([])),
         ];

-        $queries1 = Query::getByType($queries, [Query::TYPE_CURSOR_AFTER, Query::TYPE_CURSOR_BEFORE]);
+        // Test with clone (default behavior)
+        $queries1 = Query::getCursorQueries($queries);

         $this->assertCount(2, $queries1);
         foreach ($queries1 as $query) {
             $this->assertEquals(true, in_array($query->getMethod(), [Query::TYPE_CURSOR_AFTER, Query::TYPE_CURSOR_BEFORE]));
         }

         $cursor = reset($queries1);

         $this->assertInstanceOf(Query::class, $cursor);

         $cursor->setValue(new Document(['$id' => 'hello1']));

         $query1 = $queries[1];

         $this->assertEquals(Query::TYPE_CURSOR_BEFORE, $query1->getMethod());
         $this->assertInstanceOf(Document::class, $query1->getValue());
         $this->assertTrue($query1->getValue()->isEmpty()); // Cursor Document is not updated

         /**
          * Using reference $queries2 => $queries
          */
-        $queries2 = Query::getByType($queries, [Query::TYPE_CURSOR_AFTER, Query::TYPE_CURSOR_BEFORE], false);
+        $queries2 = Query::getCursorQueries($queries, false);

         $cursor = reset($queries2);
         $this->assertInstanceOf(Query::class, $cursor);
🧹 Nitpick comments (2)
src/Database/Query.php (2)

350-378: Direction helpers could throw unclear exceptions.

getCursorDirection() and getOrderDirection() throw generic \Exception with a message, but the rest of the class uses QueryException. Consider using QueryException for consistency, or at minimum add @throws docblocks.

Suggested improvement for exception consistency
+    /**
+     * `@throws` QueryException
+     */
     public function getCursorDirection(): string
     {
         if ($this->method === self::TYPE_CURSOR_AFTER) {
             return Database::CURSOR_AFTER;
         }
 
         if ($this->method === self::TYPE_CURSOR_BEFORE) {
             return Database::CURSOR_BEFORE;
         }
 
-        throw new \Exception('Invalid method: Get cursor direction on "'.$this->method.'" Query');
+        throw new QueryException('Invalid method: Get cursor direction on "'.$this->method.'" Query');
     }

+    /**
+     * `@throws` QueryException
+     */
     public function getOrderDirection(): string
     {
         // ... similar change for the throw statement
     }

532-570: New metadata fields extracted but not type-validated.

The new fields (alias, aliasRight, as, collection, attributeRight) are extracted from the decoded array but not validated to be strings before passing to the constructor. If malformed JSON provides a non-string value (e.g., "alias": []), it will cause a TypeError instead of a QueryException, which is inconsistent with the error handling for method, attribute, and values.

Add type validation for new metadata fields
         $alias = $query['alias'] ?? '';
         $aliasRight = $query['aliasRight'] ?? '';
         $as = $query['as'] ?? '';
         $collection = $query['collection'] ?? '';
 
+        foreach (['alias' => $alias, 'aliasRight' => $aliasRight, 'as' => $as, 'collection' => $collection, 'attributeRight' => $attributeRight] as $key => $value) {
+            if (!\is_string($value)) {
+                throw new QueryException("Invalid query {$key}. Must be a string, got " . \gettype($value));
+            }
+        }
+
         if (!\is_string($method)) {

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In `@src/Database/Validator/Queries/V2.php`:
- Around line 298-300: Update the exception message in the validation branch
that checks count($filters) (in class V2, where the code throws new
\Exception('Invalid query: '.\ucfirst($method).' queries require at least one
queries')); replace the grammatically incorrect phrase "at least one queries"
with "at least one query" so the message reads something like 'Invalid query:
'.\ucfirst($method).' queries require at least one query'.
♻️ Duplicate comments (1)
tests/e2e/Adapter/Scopes/DocumentTests.php (1)

4289-4293: Decode should use the encoded document.

Right now the test decodes the raw $document, so the encode→decode path isn’t actually exercised.

🐛 Proposed fix
-        $result = $database->decode($context, $document);
+        $result = $database->decode($context, $result);
🧹 Nitpick comments (2)
src/Database/Validator/Queries/V2.php (2)

77-79: Minor typo in comment.

The comment has a grammatical error: "if original data is changes" should be "if original data changes".

         /**
-         * Since $context includes Documents , clone if original data is changes.
+         * Since $context includes Documents, clone if original data changes.
          */

663-685: Use constant instead of string literal for type comparison.

Line 663 uses the string literal 'relationship' while the switch case on line 608 uses Database::VAR_RELATIONSHIP. For consistency and to avoid potential bugs if the constant value ever changes, use the constant:

-        if ($attribute['type'] === 'relationship') {
+        if ($attribute['type'] === Database::VAR_RELATIONSHIP) {

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/Database/Adapter/Mongo.php (1)

2094-2125: Inconsistent convertStdClassToArray usage between batches.

The first batch processing (line 2097) uses convertStdClassToArray($record) to handle stdClass objects in results, but subsequent batch processing (line 2120) creates the Document directly from $record without this conversion. This inconsistency could cause documents to contain unconverted stdClass objects when query results span multiple batches.

Proposed fix
                 foreach ($moreResults as $result) {
                     $record = $this->replaceChars('_', '$', (array)$result);

-                    $doc = new Document($record);
+                    $doc = new Document($this->convertStdClassToArray($record));
                     if ($removeSequence) {
                         $doc->removeAttribute('$sequence');
                     }

                     $found[] = $doc;
                 }
🤖 Fix all issues with AI agents
In `@src/Database/Database.php`:
- Around line 4891-4896: In applySelectFiltersToDocuments(), change the
attributesToKeep construction to preserve aliases and relationship roots: for
each $selectQuery use its getAttribute() but also, if $selectQuery has an alias
(e.g., getAlias() or similar), add that alias as a key to $attributesToKeep, and
if the attribute contains a dot (e.g., "rel.field"), explode on '.' and add the
first segment as a key as well; this ensures selects like "foo AS bar" and
"rel.field" keep "bar" and "rel" so nested relationship data isn't stripped
while still using getAttribute() for normal selects.
♻️ Duplicate comments (6)
tests/e2e/Adapter/Scopes/DocumentTests.php (1)

4427-4431: Decode should use encoded output (or clarify intent).

Right now decode receives the original $document, which bypasses the encode→decode round‑trip. If the goal is to validate the pipeline, pass $result instead (or add a short comment if intentional).

🔧 Suggested fix
-        $result = $database->decode($context, $document);
+        $result = $database->decode($context, $result);
src/Database/Adapter/Mongo.php (1)

2025-2040: Guard against unsupported ORDER_RANDOM queries.

The code calls $order->getOrderDirection() at line 2031 without guarding against TYPE_ORDER_RANDOM. Since getOrderDirection() throws an exception for random-order queries and this adapter reports getSupportForOrderRandom() === false, an orderRandom() query reaching this code would crash with an unclear error message. Add an explicit check similar to the SQL adapter's handling.

Proposed defensive guard
         foreach ($orderQueries as $i => $order) {
+            if ($order->getMethod() === Query::TYPE_ORDER_RANDOM) {
+                throw new DatabaseException('Random order is not supported by the Mongo adapter');
+            }
+
             $attribute  = $order->getAttribute();
             $originalAttribute = $attribute;
src/Database/Database.php (4)

5728-5732: Type normalization is skipped on update/upsert return paths.

These paths call decode() without casting(), which leaves unnormalized scalar types for adapters without native casting and makes update/upsert inconsistent with create/get/find. Please add casting($context, …) before decode() in each path.

Also applies to: 5958-5963, 6784-6788


8264-8267: Throw QueryException for unknown alias context.

These blocks still throw a generic \Exception, which bypasses query-specific handling. Replace with QueryException for consistent error flow.

Also applies to: 8363-8366


8322-8324: Casting guard is inverted.

The early-return should skip casting when the adapter does support casting, not when it doesn’t.


8809-8811: Remove unused $idAdded from relationship select injection.

$idAdded is never used and triggers PHPMD. You can safely drop it while keeping the relationship-only $id injection.

🛠️ Proposed fix
-        if (!empty($relationships)) {
-            [$queries, $idAdded] = QueryContext::addSelect($queries, Query::select('$id', system: true));
-        }
+        if (!empty($relationships)) {
+            [$queries] = QueryContext::addSelect($queries, Query::select('$id', system: true));
+        }

Based on learnings, ...

🧹 Nitpick comments (1)
src/Database/Adapter/Mongo.php (1)

1971-1972: Unused parameters $joins and $vectors are intentional for interface compatibility.

The static analyzer flags these as unused. This is expected since MongoDB doesn't support joins or vector operations, but the parameters are required to match the abstract Adapter interface. Consider adding a PHPDoc annotation to suppress the warning.

      * `@param` array<Query> $vectors
+     *
+     * `@SuppressWarnings`(PHPMD.UnusedFormalParameter) - Interface compliance; Mongo doesn't support joins/vectors
      *
      * `@return` array<Document>

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/Database/Database.php (1)

1-1: Fix PSR-12 indentation failure flagged by Pint.

The linter reports a PSR-12 statement indentation error in this file (Line 1). Please run Pint or adjust indentation to satisfy PSR-12.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In `@tests/e2e/Adapter/Scopes/JoinsTests.php`:
- Around line 34-35: The PHPDoc `@var` annotations incorrectly name the variable
`$database` while the actual variable is `$db`; update each docblock to read
`@var Database $db` so PHPStan recognizes the correct variable type—apply this
change to the docblock immediately above the `$db = $this->getDatabase();`
assignment and the other occurrences that reference `$database` in the same test
class (replace `@var Database $database` with `@var Database $db`).

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.

3 participants