Skip to content
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

fix: resolve column name handling for postgres #437

Merged
merged 4 commits into from
Nov 10, 2024

Conversation

dnkodi
Copy link
Contributor

@dnkodi dnkodi commented Nov 6, 2024

This PR addresses an issue raised in #390 , where TypeORM fails to properly quote camelCase aliases in PostgreSQL, leading to errors when querying project statistics and exports endpoint. TypeORM has several open issues, including (typeorm/typeorm#10961), related to camelCase alias handling in PostgreSQL that remain unresolved.

As a temporary workaround, this PR replaces camelCase aliases with snake_case until TypeORM provides a permanent fix.

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features
    • Introduced a utility function to dynamically resolve database column names, enhancing query flexibility.
  • Improvements
    • Updated SQL query handling in the export and project stats functionalities for better maintainability.
  • Bug Fixes
    • Addressed issues with column naming conventions in PostgreSQL to ensure proper query execution.

Copy link

vercel bot commented Nov 6, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
traduora-docs-co ✅ Ready (Inspect) Visit Preview 💬 Add feedback Nov 7, 2024 1:46pm

Copy link

coderabbitai bot commented Nov 6, 2024

Walkthrough

The changes in this pull request introduce a new utility function, resolveColumnName, in the alias-helper.ts file, which dynamically resolves column names based on the database type. This function is then utilized in the ExportsController and ProjectStatsController classes to enhance the flexibility of SQL queries by replacing static string references with dynamic resolution for specific fields. The overall control flow and error handling in the methods remain unchanged, ensuring consistent functionality.

Changes

File Change Summary
api/src/controllers/exports.controller.ts Added import for resolveColumnName; updated SQL queries in export method to use dynamic column resolution.
api/src/controllers/project-stats.controller.ts Added import for resolveColumnName; updated SQL queries in getStats method to use dynamic column resolution.
api/src/utils/alias-helper.ts Introduced new method resolveColumnName(columnName: string): string for dynamic column name resolution.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant ExportsController
    participant ProjectStatsController
    participant AliasHelper

    Client->>ExportsController: Request export
    ExportsController->>AliasHelper: resolveColumnName(projectLocaleId)
    AliasHelper-->>ExportsController: Returns resolved column name
    ExportsController->>Database: Execute export query with resolved names
    Database-->>ExportsController: Returns export data
    ExportsController-->>Client: Sends exported data

    Client->>ProjectStatsController: Request project stats
    ProjectStatsController->>AliasHelper: resolveColumnName(projectLocale)
    AliasHelper-->>ProjectStatsController: Returns resolved column name
    ProjectStatsController->>Database: Execute stats query with resolved names
    Database-->>ProjectStatsController: Returns stats data
    ProjectStatsController-->>Client: Sends project stats data
Loading

Poem

🐰 In the code where rabbits play,
A new function brightens the day.
With names resolved, oh what a sight,
Queries dance in the soft moonlight.
Flexibility hops, errors take flight,
In our code garden, everything's right! 🌼


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between e198780 and 0cb2244.

📒 Files selected for processing (1)
  • api/src/controllers/project-stats.controller.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • api/src/controllers/project-stats.controller.ts

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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

@dnkodi dnkodi changed the title fix: adjust alias to work with postgres fix: resolve column name handling for postgres Nov 7, 2024
Copy link

@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: 2

🧹 Outside diff range and nitpick comments (3)
api/src/utils/alias-helper.ts (1)

4-6: Good documentation and clean implementation.

The code is well-documented with a clear reference to the TypeORM issue. The utility function provides a clean abstraction that can be easily removed once TypeORM fixes the underlying issue.

Consider caching the converted names for frequently accessed columns to improve performance:

+const columnNameCache = new Map<string, string>();
+
 export const resolveColumnName = (columnName: string): string => {
+  const cached = columnNameCache.get(columnName);
+  if (cached) return cached;
+
   // Convert the column name to snake_case if needed
   if (config.db.default.type === 'postgres') {
-    return snakeCase(columnName);
+    const converted = snakeCase(columnName);
+    columnNameCache.set(columnName, converted);
+    return converted;
   }
+  columnNameCache.set(columnName, columnName);
   return columnName;
 }
api/src/controllers/project-stats.controller.ts (1)

49-53: Consider enhancing type safety and error handling

While the current implementation works, consider these improvements:

  1. Use TypeORM's metadata to validate column names at runtime
  2. Add error handling for cases where database type detection fails
  3. Consider creating constants for frequently used column names

Example enhancement:

// Create constants for column names
const COLUMN_NAMES = {
  LOCALE_CODE: 'localeCode',
  PROJECT_LOCALE: 'projectLocale'
} as const;

// Use constants in query
.createQueryBuilder(resolveColumnName(COLUMN_NAMES.PROJECT_LOCALE))
.leftJoin(`${resolveColumnName(COLUMN_NAMES.PROJECT_LOCALE)}.translations`, 'translations')
api/src/controllers/exports.controller.ts (1)

117-120: Consider extracting duplicate query builder logic.

While the column name resolution is correctly implemented, there's duplicate query building logic between the main locale and fallback locale sections. Consider extracting this into a reusable method.

+  private buildLocaleQuery(projectId: string, projectLocaleId: string) {
+    return this.termRepo
+      .createQueryBuilder('term')
+      .leftJoinAndSelect(
+        'term.translations',
+        'translation',
+        `translation.${resolveColumnName('projectLocaleId')} = :projectLocaleId`,
+        { projectLocaleId }
+      )
+      .where(`term.${resolveColumnName('projectId')} = :projectId`, { projectId })
+      .orderBy('term.value', 'ASC');
+  }

Then use it in both places:

// Main locale
const queryBuilder = this.buildLocaleQuery(projectId, projectLocale.id);
if (query.untranslated) {
  queryBuilder.andWhere("translation.value = ''");
}

// Fallback locale
const fallbackTermsWithTranslations = await this.buildLocaleQuery(
  projectId,
  fallbackProjectLocale.id
).getMany();
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 454d9bf and bd14582.

📒 Files selected for processing (3)
  • api/src/controllers/exports.controller.ts (4 hunks)
  • api/src/controllers/project-stats.controller.ts (2 hunks)
  • api/src/utils/alias-helper.ts (1 hunks)
🔇 Additional comments (4)
api/src/utils/alias-helper.ts (1)

1-2: LGTM! Appropriate use of TypeORM's built-in utility.

Good choice using TypeORM's snakeCase utility instead of implementing custom string conversion.

api/src/controllers/project-stats.controller.ts (2)

15-15: LGTM: Import of resolveColumnName utility

The import is correctly placed and properly utilized in the file.


49-53: LGTM: Query builder modifications for PostgreSQL compatibility

The changes appropriately use resolveColumnName to handle camelCase to snake_case conversion for PostgreSQL compatibility. The implementation is consistent across all query builder methods.

Let's verify the implementation:

api/src/controllers/exports.controller.ts (1)

74-77: LGTM! Column name resolution implemented correctly.

The dynamic column name resolution is properly implemented for both the join condition and where clause, which should resolve the PostgreSQL camelCase alias issues.

api/src/utils/alias-helper.ts Outdated Show resolved Hide resolved
api/src/controllers/exports.controller.ts Outdated Show resolved Hide resolved
Copy link

@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 and nitpick comments (1)
api/src/utils/alias-helper.ts (1)

4-6: Add JSDoc documentation for better maintainability.

While the comment explains the issue, adding JSDoc documentation would improve maintainability by clearly documenting the function's purpose, parameters, and return value.

 // TypeORM fails to properly quote camelCase aliases with PostgreSQL
 // https://github.com/typeorm/typeorm/issues/10961
+/**
+ * Resolves column names to be compatible with the current database type.
+ * For PostgreSQL, converts camelCase to snake_case as a workaround for TypeORM's quoting issue.
+ * @param columnName - The original column name
+ * @returns The resolved column name appropriate for the current database
+ * @throws {Error} When columnName is empty
+ */
 export const resolveColumnName = (columnName: string): string => {
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between bd14582 and e198780.

📒 Files selected for processing (2)
  • api/src/controllers/exports.controller.ts (3 hunks)
  • api/src/utils/alias-helper.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • api/src/controllers/exports.controller.ts
🔇 Additional comments (3)
api/src/utils/alias-helper.ts (3)

1-2: LGTM! Appropriate imports used.

The imports are minimal and necessary, using TypeORM's built-in string utilities appropriately.


7-9: Input validation implemented correctly.

The suggested input validation has been properly implemented.


11-17: Add type safety for database configuration.

While the implementation is correct, consider adding type safety for the database configuration to prevent potential runtime errors.

+type SupportedDatabase = 'postgres' | 'mysql' | 'sqlite';
+
 export const resolveColumnName = (columnName: string): string => {
   if (!columnName) {
     throw new Error('Column name cannot be empty');
   }
 
   // convert only for postgres until typeorm has a fix
-  if (config.db.default.type === 'postgres') {
+  const dbType = config.db.default?.type as SupportedDatabase;
+  if (!dbType) {
+    throw new Error('Database type not configured');
+  }
+  
+  if (dbType === 'postgres') {
     return snakeCase(columnName);
   }
 
   return columnName;
 };

Let's verify the database configuration usage across the codebase:

@evereq evereq merged commit 047924e into ever-co:develop Nov 10, 2024
14 checks passed
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