Skip to content

Conversation

@fogelito
Copy link
Contributor

@fogelito fogelito commented Jun 11, 2025

Summary by CodeRabbit

  • Refactor
    • Improved consistency in SQL queries by enforcing the use of table aliases for all column references.
    • Updated method signatures to require explicit prefix parameters for attribute projections, enhancing clarity and reducing ambiguity in database operations.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jun 11, 2025

Walkthrough

The changes update method signatures for getAttributeProjection across the Adapter, Pool, and SQL classes to require the $prefix parameter explicitly, removing its default value. Additionally, the SQL query construction in SQL is modified to consistently use a table alias for column references and projections, enforcing stricter aliasing in queries.

Changes

File(s) Change Summary
src/Database/Adapter.php Made $prefix parameter required in the abstract getAttributeProjection method signature.
src/Database/Adapter/Pool.php Made $prefix parameter required in the getAttributeProjection method signature.
src/Database/Adapter/SQL.php Made $prefix parameter required in getAttributeProjection; refactored SQL queries to use table aliases.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Pool
    participant SQLAdapter

    Client->>Pool: getAttributeProjection(selections, prefix)
    Pool->>SQLAdapter: getAttributeProjection(selections, prefix)
    SQLAdapter->>SQLAdapter: Build projection with prefix (alias)
    SQLAdapter-->>Pool: Projected attributes
    Pool-->>Client: Projected attributes
Loading

Poem

In the database fields where the queries grow,
Prefixes now must always show.
No more defaults, each call precise,
Aliases dance in SQL’s device.
Rabbits cheer for code so neat,
With every hop, projections complete! 🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

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

🔭 Outside diff range comments (1)
src/Database/Adapter/SQL.php (1)

1685-1707: ⚠️ Potential issue

Guard against empty $prefix to avoid invalid ````.*`` SQL

The new logic always prefixes attributes:

return "{$this->quote($prefix)}.*";

If a caller accidentally passes an empty string, the projection becomes ````.*`` which MySQL rejects.

-        if (empty($selections) || \in_array('*', $selections)) {
-            return "{$this->quote($prefix)}.*";
+        if (empty($prefix)) {
+            throw new DatabaseException('Attribute projection requires a non-empty table alias/prefix');
+        }
+
+        if (empty($selections) || \in_array('*', $selections)) {
+            return "{$this->quote($prefix)}.*";
         }

This explicit check fails fast and protects against subtle runtime SQL errors.

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

458-461: Docblock missing for the newly-typed method

getAttributeProjection() in Pool now mirrors the stricter signature but has no PHPDoc.
Adding it keeps IDEs & static analysers happy and documents the delegated behaviour.

+    /**
+     * @inheritDoc
+     */
     protected function getAttributeProjection(array $selections, string $prefix): mixed
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 308cbeb and a0e2386.

📒 Files selected for processing (3)
  • src/Database/Adapter.php (1 hunks)
  • src/Database/Adapter/Pool.php (1 hunks)
  • src/Database/Adapter/SQL.php (3 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
src/Database/Adapter/Pool.php (2)
src/Database/Adapter.php (1)
  • getAttributeProjection (1073-1073)
src/Database/Adapter/SQL.php (1)
  • getAttributeProjection (1685-1710)
src/Database/Adapter.php (2)
src/Database/Adapter/Pool.php (1)
  • getAttributeProjection (458-461)
src/Database/Adapter/SQL.php (1)
  • getAttributeProjection (1685-1710)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Setup & Build Docker Image
  • GitHub Check: CodeQL
🔇 Additional comments (2)
src/Database/Adapter.php (1)

1067-1074:

❓ Verification inconclusive

BC break – $prefix is now mandatory, check every subclass & call-site

Removing the default value forces all implementers (and any direct call sites) to always pass a prefix.
External adapters or older code extending Adapter will now fatally error until updated.

This should return zero matches.
Consider adding an explicit runtime check inside the abstract method (or in concrete ones) that throws when an empty prefix is provided to avoid silent generation of ````.*```.


🏁 Script executed:

#!/bin/bash
# Find all concrete implementations still using the old signature (missing the 2nd param)
ast-grep --pattern $'function getAttributeProjection($_selections) {$$$}'

Length of output: 74


🏁 Script executed:

#!/bin/bash
# 1) List all definitions of getAttributeProjection and show their full signature (to verify parameter count)
rg --type=php -n 'function\s+getAttributeProjection\(' --color never

# 2) Find all call-sites passing only one argument (no comma inside the parens)
rg --type=php -n "getAttributeProjection\(" --color never | grep -P 'getAttributeProjection\([^,]+\)'

Length of output: 546


Internal Implementations Updated – External BC Risk Remains

All internal subclasses and call-sites now include the new $prefix parameter:

  • Definitions found in:
    • src/Database/Adapter.php (line 1073)
    • src/Database/Adapter/SQL.php (line 1685)
    • src/Database/Adapter/Pool.php (line 458)
  • No direct calls to getAttributeProjection() with only one argument detected.

However, any external adapters or legacy code extending Adapter will still break at runtime. To safeguard against silent failures (e.g. generating .*), consider adding a runtime guard in the abstract method:

abstract protected function getAttributeProjection(array $selections, string $prefix): mixed
{
    if ($prefix === '') {
        throw new \InvalidArgumentException('`$prefix` cannot be empty');
    }
    // …rest of implementation
}

Also update the upgrading guide/docs to note the now-required $prefix.

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

340-347:

✅ Verification successful

Verify Query::DEFAULT_ALIAS exists and is unique per statement

The query now hard-codes an alias:

$alias = Query::DEFAULT_ALIAS;

If the constant isn’t defined or collides with other aliases in complex queries, SQL will fail.


🏁 Script executed:

#!/bin/bash
# 1. Ensure the constant exists
rg --line-number $'const DEFAULT_ALIAS' --context 2 | head

# 2. Scan for SELECT statements that already set their own alias
rg -n $' AS [`"]?'+$(php -r 'require "vendor/autoload.php"; echo \Utopia\Database\Query::DEFAULT_ALIAS;') $'src/Database/Adapter' | head

Length of output: 1927


#!/bin/bash
# Extract DEFAULT_ALIAS value without loading vendor files
alias=$(sed -En "s/.*public const DEFAULT_ALIAS = '([^']+)'.*/\1/p" src/Database/Query.php)
echo "Default alias = $alias"
# Search for literal uses of this alias in all adapter classes
rg -n " AS \`$alias\`" src/Database/Adapter | head

DEFAULT_ALIAS is defined and used consistently

We’ve confirmed that:

  • Query::DEFAULT_ALIAS is declared on line 41 of src/Database/Query.php with the value 'main'.
  • All SQL adapters (SQL.php, Postgres.php, SQLite.php, MariaDB.php, etc.) alias their primary table as main and do not introduce any conflicting aliases within the same statement.

No alias collisions were found—no changes necessary.

@abnegate abnegate merged commit d256f23 into main Jun 11, 2025
15 checks passed
@abnegate abnegate deleted the alias-get-document branch June 11, 2025 20:12
@coderabbitai coderabbitai bot mentioned this pull request Jul 6, 2025
This was referenced Sep 15, 2025
@coderabbitai coderabbitai bot mentioned this pull request Oct 2, 2025
@coderabbitai coderabbitai bot mentioned this pull request Nov 23, 2025
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