8000 fix (nocodb): multi user replace for order by fendy3002 · Pull Request #11370 · nocodb/nocodb · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

fix (nocodb): multi user replace for order #11370

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 15, 2025

Conversation

fendy3002
Copy link
Collaborator

Change Summary

fix (nocodb): multi user replace for order

Change type

  • fix: (bug fix for the user, not a fix to a build script)

Copy link
Contributor
coderabbitai bot commented May 14, 2025
📝 Walkthrough

Walkthrough

The changes introduce database-specific helper functions to generate SQL expressions for replacing delimited user-related columns with mapped values during group-by operations. The groupBy function now conditionally uses PostgreSQL or SQLite3-specific implementations, while retaining the original logic for other databases. No public API changes were made.

Changes

Files/Paths Change Summary
packages/nocodb/src/db/BaseModelSqlv2/group-by.ts Refactored group-by logic to use database-specific helper functions for user-related column replacements.
packages/nocodb/src/db/aggregations/pg.ts Added replaceDelimitedWithKeyValuePg function for PostgreSQL-specific delimited key-value replacements.
packages/nocodb/src/db/aggregations/sqlite3.ts Added replaceDelimitedWithKeyValueSqlite3 function for SQLite3-specific delimited key-value replacements.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant groupBy
    participant PG_Helper as replaceDelimitedWithKeyValuePg
    participant SQLITE_Helper as replaceDelimitedWithKeyValueSqlite3
    participant DB

    Client->>groupBy: Request group-by with user-related sorting
    groupBy->>groupBy: Detect database client type
    alt PostgreSQL
        groupBy->>PG_Helper: Build replacement SQL expression
    else SQLite3
        groupBy->>SQLITE_Helper: Build replacement SQL expression
    else Other DB
        groupBy->>groupBy: Use original nested REPLACE logic
    end
    groupBy->>DB: Execute group-by query with constructed SQL
    DB-->>groupBy: Return results
    groupBy-->>Client: Return grouped results
Loading

Possibly related PRs

  • nocodb/nocodb#11349: The main PR extends the approach introduced in the retrieved PR by adding database-specific implementations for user-related SQL expression replacements, building on the union-based subquery method originally established in the retrieved PR.

Suggested reviewers

  • pranavxc

Tip

⚡️ Faster reviews with caching
  • CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.

Enjoy the performance boost—your workflow just got faster.

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 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.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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.
8000

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

🧹 Nitpick comments (1)
packages/nocodb/src/db/BaseModelSqlv2/group-by.ts (1)

1254-1261: Consider refactoring this part to use the new helper functions.

For consistency, this code block in the bulkList function should also be updated to use the new database-specific helper functions similar to what was done in the groupBy function. This would ensure consistent behavior and maintainability across the codebase.

- // create nested replace statement for each user
- const finalStatement = baseUsers.reduce((acc, user) => {
-   const qb = baseModel.dbDriver.raw(`REPLACE(${acc}, ?, ?)`, [
-     user.id,
-     user.display_name || user.email,
-   ]);
-   return qb.toQuery();
- }, baseModel.dbDriver.raw(`??`, [columnName]).toQuery());
+ let finalStatement = '';
+ if (baseModel.dbDriver.clientType() === 'pg') {
+   finalStatement = `(${replaceDelimitedWithKeyValuePg({
+     knex: baseModel.dbDriver,
+     needleColumn: columnName,
+     stack: baseUsers.map((user) => ({
+       key: user.id,
+       value: user.display_name || user.email,
+     })),
+   })})`;
+ } else if (baseModel.dbDriver.clientType() === 'sqlite3') {
+   finalStatement = `(${replaceDelimitedWithKeyValueSqlite3({
+     knex: baseModel.dbDriver,
+     needleColumn: columnName,
+     stack: baseUsers.map((user) => ({
+       key: user.id,
+       value: user.display_name || user.email,
+     })),
+   })})`;
+ } else {
+   // use the original replace
+   finalStatement = baseUsers.reduce((acc, user) => {
+     const qb = baseModel.dbDriver.raw(`REPLACE(${acc}, ?, ?)`, [
+       user.id,
+       user.display_name || user.email,
+     ]);
+     return qb.toQuery();
+   }, baseModel.dbDriver.raw(`??`, [columnName]).toQuery());
+ }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6e42b04 and c84f336.

📒 Files selected for processing (3)
  • packages/nocodb/src/db/BaseModelSqlv2/group-by.ts (3 hunks)
  • packages/nocodb/src/db/aggregations/pg.ts (2 hunks)
  • packages/nocodb/src/db/aggregations/sqlite3.ts (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
packages/nocodb/src/db/BaseModelSqlv2/group-by.ts (2)
packages/nocodb/src/db/aggregations/pg.ts (1)
  • replaceDelimitedWithKeyValuePg (413-453)
packages/nocodb/src/db/aggregations/sqlite3.ts (1)
  • replaceDelimitedWithKeyValueSqlite3 (426-466)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: release-docker / buildx
  • GitHub Check: pre-build-for-playwright / playwright
  • GitHub Check: unit-tests-pg
  • GitHub Check: unit-tests
🔇 Additional comments (6)
packages/nocodb/src/db/BaseModelSqlv2/group-by.ts (2)

6-7: LGTM: Good addition of database-specific helper imports.

The two imports for database-specific replacements will make the code more maintainable by separating database-specific logic into appropriate files.

Also applies to: 20-20


306-334: Good database-specific SQL generation approach.

This refactoring improves maintainability by using database-specific helpers for replacing user IDs with names. The code now cleanly handles:

  • PostgreSQL-specific implementation using string_to_array and unnest
  • SQLite3-specific implementation using json_each
  • Fallback to nested REPLACE calls for other databases

The solution is more modular and easier to maintain than the previous approach.

packages/nocodb/src/db/aggregations/pg.ts (2)

11-11: LGTM: Appropriate type import.

The addition of the CustomKnex type import is needed for the new function parameter typing.


413-453: Well-implemented PostgreSQL-specific replacer function.

This function effectively handles replacing delimited user IDs with display names specifically for PostgreSQL. The implementation:

  1. Creates a key-value map through a UNION ALL query
  2. Splits the delimited input column using PostgreSQL's string_to_array and unnest
  3. Performs a left join to map keys to values
  4. Aggregates results back with string_agg
  5. Properly uses parameter binding for SQL injection prevention

The function is well-structured and uses PostgreSQL's features effectively.

packages/nocodb/src/db/aggregations/sqlite3.ts (2)

14-14: LGTM: Appropriate type import.

The addition of the CustomKnex type import is needed for the new function parameter typing.


426-466: Well-implemented SQLite3-specific replacer function.

This function effectively handles replacing delimited user IDs with display names specifically for SQLite3. The implementation:

  1. Creates a key-value map through a UNION ALL query
  2. Cleverly splits the delimited input using SQLite's json_each by first converting the delimited string to a JSON array
  3. Performs a left join to map keys to values
  4. Aggregates results back with GROUP_CONCAT
  5. Properly uses parameter binding for SQL injection prevention

The approach is elegant considering SQLite3's more limited string manipulation capabilities compared to PostgreSQL.

@fendy3002
Copy link
Collaborator Author

the unit test error is a fluke. Tried locally. Will monitor if keeps happening.

@fendy3002 fendy3002 merged commit b58f87b into develop May 15, 2025
22 of 23 checks passed
@fendy3002 fendy3002 deleted the nc-fix/multi-user-replace-order branch May 15, 2025 07:26
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.

2 participants
0